// 管理员后台js
// noinspection JSUnresolvedReference

"use strict";
const js_configurg = {
    loading_time_out: 0,//15秒 loading等待时间，超过此时间将自动取消loading
}

/**
 * 防抖函数
 * @param fn
 * @param delay
 * @param immediate
 * @returns {(function(): void)|*}
 */
function debounce(fn, delay = 500, immediate = false) {
    let timer;
    return function () {
        let _this = this;
        let opt = arguments;

        timer && clearTimeout(timer);
        if (immediate) {
            let call = !timer;
            timer = setTimeout(function () {
                timer = false;
            }, delay);
            call && fn.apply(_this, opt);
        } else {
            timer = setTimeout(function () {
                fn.apply(_this, opt);
            }, delay);
        }
    }
}

// 登录
function login() {
    const form = document.loginForm;
    form.userName.focus();
    //返回验证码
    const checkNumImg = '#checkNumImg';
    $(checkNumImg).on('click', function () {
        $(this).attr('src', `${root}library/libData.html?type=proveImg&random=${Math.random()}`);
    });
    //按下回车键时，触发登录按钮
    const subButton = '[subButton=yes]';
    $(document).on('keyup', function (event) {
        if (event.keyCode === 13) {
            $(subButton).click();
        }
    });
    //判断当前是否在iframe中
    if (window.top !== window.self) {
        window.top.location.reload();
    }
}


/***客户管理-跟进记录快捷按钮***/
function textQuick(obj) {
    document.followForm.text.value = $(obj).html();
}

// 验证表单数据
function validate(obj) {
    const validation = {
        userName: '用户名', password: '密码', prove: '验证码', company: '企业名称',
    };

    const name = $(obj).attr('name');
    let errorTpl = '';

    if ($(obj).val().trim().length <= 0) {
        errorTpl = `<span class='errormsg'>请输入${validation[name]}</span>`;
        $(obj).after(errorTpl);
    } else {
        $(obj).nextAll('.errormsg').remove();
    }

    let flag = true;
    const fields = Object.keys(validation);
    const inputs = fields.map((field) => $(`[name="${field}"]`));
    for (let i = 0; i < inputs.length; i++) {
        const input = inputs[i];
        const value = input.val() ? input.val().trim() : '';
        if (value.length <= 0) {
            flag = false;
            break;
        }
    }
    if (flag) {
        const submitBtn = $('#login-submit');
        if (!submitBtn.hasClass('disabled')) {
            submitBtn.addClass('disabled');
        }
    }
}

/** home 日期查询 */
function searchLine(value, fun, cla = 'homepage') {
    $.post(root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun, {
        startMoon: value
    }, function (res) {
        let obj = '#' + fun + 'Html';
        $(obj).empty().append(res.html);
    }, 'json')
}

/***iframe框架***/
//点击主页
function homepage() {
    //iframe切换
    $("[iframeName]").css("display", "none");
    $("[iframeName=主页]").css("display", "block");
    //顶部页卡切换
    $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
    $("#homepage").addClass("iframeTitleNow");
    //清理左侧导航高亮选择效果
    $("[iframeHref]").removeClass("frameLeftHover");
}

//顶部导航向左移动
function pageLeft() {
    var widthTitle = parseFloat($("#iframeTitle").css("width"));
    var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
    var left = parseFloat($("#iframeTitle > ul").css("left"));
    if (left < 0) {
        left += 137;
        $("#iframeTitle > ul").css("left", left + "px");
    }
    //left参数值可能已改变
    if (left >= 0) {
        $("#pageLeft > img").attr("src", root + "img/control/pageLeft.svg");
    }
    if (widthUl + left > widthTitle) {
        $("#pageRight > img").attr("src", root + "img/control/pageRightLight.svg");
    }
    console.log("widthTitle：" + widthTitle + ",widthUl:" + widthUl + ",left:" + left);
}

//顶部导航向右移动
function pageRight() {
    var widthTitle = parseFloat($("#iframeTitle").css("width"));
    var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
    var left = parseFloat($("#iframeTitle > ul").css("left"));
    if (widthUl + left > widthTitle) {
        left -= 137;
        $("#iframeTitle > ul").css("left", left + "px");
    }
    //left参数值可能已改变
    if (left < 0) {
        $("#pageLeft > img").attr("src", root + "img/control/pageLeftLight.svg");
    }
    if (widthUl + left <= widthTitle) {
        $("#pageRight > img").attr("src", root + "img/control/pageRight.svg");
    }
    console.log("widthTitle：" + widthTitle + ",widthUl:" + widthUl + ",left:" + left);
}

//缩放左侧菜单
function shrink(obj) {
    var left = root + "img/control/moveLeft.svg";
    var right = root + "img/control/moveRight.svg";
    var now = $(obj).children("img").attr("src");
    if (now === left) {
        $(obj).children("img").attr("src", right);
        $(obj).children("img").attr("title", "显示左侧菜单");
        $("#frameLeft, #adLogo").hide();
        $("#homepage, #pageLeft, #iframeTitle, #menu, #shrink, #frameRight").css({
            "left": "-=165px"
        });
    } else {
        $(obj).children("img").attr("src", left);
        $(obj).children("img").attr("title", "隐藏左侧菜单");
        $("#frameLeft, #adLogo").show();
        $("#homepage, #pageLeft, #menu, #iframeTitle, #shrink, #frameRight").css({
            "left": "+=165px"
        });
    }
}


// 加载二维码函数
function loadQRcode() {
    // 从后台返回data
    const data = '做企业管理软件，找雨木科技。\n\n 技术联系电话：023-88692248 18581286862'
    let qrSrc = root + 'pay/wxpay/wxScanPng?url=' + data
    $('#login-qr').attr('src', qrSrc)
}

$(function () {
    Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };
    // 登录账号和二维码切换
    $(document).on('click', "#loginSwitch", function () {
        // 暂时隐藏
        // return false
        let current = $(this).attr('current'), imgSrc = ''
        if (current === 'account') {
            $('#login-main-account, .login-bottom').hide()
            $('#login-main-qr').show()
            $(this).attr('current', 'QRcode')
            imgSrc = root + 'img/websiteImg/pc_login.png'
            let did = $("input[name='did']").val();
            // loadQRcode()
            // let url = encodeURI(root+'control/qyLoginClass?did='+did);
            let css = encodeURI(root + 'static/stylesheet/login.css');
            $.post(root + 'library/libData.html?type=getPara', {did: did}, function (res) {
                new WwLogin({
                    "id": "login-main-qr",
                    "appid": res.appid,
                    "agentid": res.agentid,
                    "redirect_uri": res.url,
                    "state": res.nonstr,
                    "href": css,
                    "lang": "zh",
                });
            }, 'json')

        } else {
            $(this).attr('current', 'account')
            $('#login-main-account, .login-bottom').show()
            $('#login-main-qr').hide()
            imgSrc = root + 'img/websiteImg/qr_login.png'
        }
        $(this).find('img').attr('src', imgSrc)
    });

    // 会员中心角标
    // $("#user").hover(function () {
    //     $('.userList').show()
    // }, function () {
    //     $('.userList').hover(function () {
    //         $('.userList').show()
    //     }, function () {
    //         $('.userList').hide()
    //     })
    // })
    $("#user").bind('click', function () {
        let display = $(".userList").css('display');
        if (display === 'none') {
            $('.userList').show()
        } else {
            $('.userList').hide()
        }
    })

    // 申请单状态
    $("#record").hover(function () {
        $('.stateBlock').show()
    }, function () {
        $('.stateBlock').hover(function () {
            $('.stateBlock').show()
        }, function () {
            $('.stateBlock').hide()
        })
    })

    // 表单多选
    $("#body").on('click', ".winAuto .tableMany tr", function () {
        //表头不触发
        if ($(this).html().indexOf('checkAll') === -1) {
            let radio = $(this).find("td").find("input[type='radio']")
            let checkbox = $(this).find("td").find("input[type='checkbox']")
            if (radio.length > 0) {
                radio.prop("checked", true)
            } else if (checkbox.length > 0) {
                if (checkbox.is(":checked")) {
                    checkbox.prop('checked', false)
                } else {
                    checkbox.prop('checked', true)
                }
            }
        }
    })
    // 自定义字段显示
    $(document).on('click', ".field-setting", function (that) {
        // let panel = $(that.target).next(".field-panel")
        // const display = panel.css('display')
        // if (display === 'none') {
        //     panel.show()
        // } else {
        //     panel.hide()
        // }
        let pageStr = $(this).parents('.tableMany').eq(0).data('page');
        let fields = $(this).parents('.tableMany').eq(0).data('all');
        layer('homepage', 'tableFieldFrame', {fieldName: fields, pageStr: pageStr})
    })
    // 自定义字段全选
    // $(document).on('click', '[name="checkAllField"]', function () {
    //     if ($(this).is(":checked")) {
    //         $("[name='fields[]']").prop('checked', true)
    //     } else {
    //         $("[name='fields[]']").prop('checked', false)
    //     }
    //     // 同步数据
    //     syncData(document, $(this).parents('[pagediv]').attr('pagediv'))
    // })
    //
    // $(document).on('click', "[name='fields[]']", function () {
    //     syncData(document, $(this).parents('[pagediv]').attr('pagediv'))
    // })
    $(document).on('click', '#body', function (e) {
        let pageMenu = $("#pageMenu")
        let target = $("#fieldPanel")
        if (target.length > 0) {
            if (pageMenu.length > 0) {
                // 使用jQuery选择所有具有相同class选择器的元素
                var pageDivs = $('.pageDiv');
                // 遍历每个元素并检查其显示状态
                pageDivs.each(function () {
                    var $pageDiv = $(this);
                    // 使用jQuery方法检查元素的可见性
                    if ($pageDiv.is(':visible')) {
                        if ($pageDiv.find(".fixed-thead").length > 0) {
                            target = $pageDiv.find(".fixed-thead-head").find(".field-panel")
                        } else {
                            target = $pageDiv.find(".field-panel")
                        }
                        let click_target = $pageDiv.find(".field-setting")
                        let disply = target.css('display')
                        if (!target.is(e.target) && target.has(e.target).length === 0 && click_target.has(e.target).length === 0 && disply !== 'none' && !click_target.is(e.target)) {
                            target.hide();
                            if ($("#renovate").attr("url")) {
                                //页卡切换时会保存菜单关键字在renovate的url中
                                location.href = $("#renovate").attr("url");
                            } else {
                                location.reload();
                            }
                        }
                    }
                });
            } else {
                let click_target = $("#fieldSetting")
                let disply = target.css('display')
                if (!target.is(e.target) && target.has(e.target).length === 0 && click_target.has(e.target).length === 0 && disply !== 'none' && !click_target.is(e.target)) {
                    target.hide();
                    if ($("#renovate").attr("url")) {
                        //页卡切换时会保存菜单关键字在renovate的url中
                        location.href = $("#renovate").attr("url");
                    } else {
                        location.reload();
                    }
                }
            }
        }
    })

    // 同步数据
    function syncData(document, element) {
        let obj, formData
        if (element === undefined || element === 'undefined') {
            obj = $(document).find('[searchformhtml] > form')
        } else {
            obj = $('[pagediv="' + element + '"]').find('[searchformhtml] > form')
        }
        // 数据去重
        const page = obj.find('[name="page"]').val()
        formData = obj.serialize()
        if (page.length > 0) {
            const pageStr = `page=${page}`
            formData = formData.split(pageStr)[0] + pageStr
        }
        $.post(root + 'control/adIndex.html?cla=homepage&fun=setField', formData, function (res) {
            if (res.code === 0) {
                msg(res.warn, 'error')
            }
        }, 'json')
    }

    // 界面排序
    $(document).on('click', '[sort-key] > span:not(".drag")', function () {
        // 判断是否有表格固定框架
        const has = $(document).find('.fixed-thead').length
        const ascObj = $(this).parent().find('.table-sort-asc'), descObj = $(this).parent().find('.table-sort-desc')

        let table = (has === 1) ? $(this).closest('.fixed-thead').find('.fixed-thead-body > table').eq(0) : $(this).parents('table').eq(0)
        let rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).parent().index()))
        this.asc = !this.asc
        if (!this.asc) {
            rows = rows.reverse()
            ascObj.removeClass('table-sort-asced')
            descObj.addClass('table-sort-desced')
        } else {
            ascObj.addClass('table-sort-asced')
            descObj.removeClass('table-sort-desced')
        }
        $(this).parent().siblings().find('i').removeClass('table-sort-asced table-sort-desced')
        table.children('tbody').empty().html(rows)
    })

    function comparer(index) {
        return function (a, b) {
            let valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text();
    }

    //分类选择器
    $(document).on('click', '#layerBut', this, function () {
        let parent = $(this).parents('span#type-box'), name = $(this).data('name'),
            obj = parent.find('[name="' + name + '"]'), id = rand()
        if (obj.length > 0) {
            id = obj.attr('id')
        } else {
            let tpl = `
            <input id='` + id + `' type='hidden' name='materialTypeId'>`
            parent.append(tpl)
        }
        let params = {}

        // 类型
        switch ($(this).attr('id')) {
            case 'layerBut'://单独作为员工选择器时
                params = {
                    id: id, all: true, other: 'selector',
                }
                break;
        }
        // 调用此方法需保证 当前页面有 js-party-select-result-list 和 该id 的隐藏域
        layer('examine', 'materialTypeTree', params)
        $(this).find('.placeholder').remove()
    })
    textareaHeightHandle($('.edit4'))

})

/**
 * 文本域高度根据内容设置
 */
function textareaHeightHandle(containerNode) {
    // 当页面加载后，找到所有 textarea 元素
    containerNode.find('textarea').each(function () {
        // 获取当前 textarea 的内容
        var content = $(this).val();
        // 创建一个临时的 textarea 用于计算高度
        var tempTextarea = $('<textarea>').css({
            position: 'absolute', left: '-9999px', // 移出屏幕外
            width: $(this).width(), // 继承原始宽度
            height: $(this).height(), // 继承原始高度
            fontSize: $(this).css('font-size'), // 继承原始字体大小
            fontFamily: $(this).css('font-family'), // 继承原始字体样式
            lineHeight: $(this).css('line-height'), // 继承原始行高
            resize: 'none', // 禁止用户调整大小
            padding: $(this).css('padding'), // 继承原始填充样式
            border: $(this).css('border') // 继承原始边框样式
        }).appendTo('body').val(content);

        // 计算高度
        var height = tempTextarea[0].scrollHeight;
        // 设置 textarea 的高度
        $(this).css('height', height + 'px');

        // 移除临时的 textarea
        tempTextarea.remove();
    });
}
/**
 * 获取弹窗查询区域高度
 */
function layerSearchHeightHandle(layerId) {
    var layerEle = $("[layerId='"+layerId+"']")
    var winAutoHeight = layerEle.find('.winAuto').height()
    var searchHeight = layerEle.find('.search').outerHeight(true)
    layerEle.find('.winBody').css('height', (winAutoHeight - searchHeight - 10) + 'px');
}

/**
 * 页面加载滚动到上次定位的位置
 */
function initScrollPosition() {
    // 判断当前窗口是否在 iframe 中
    if (window.parent !== window) {
        var frameSrc = window.frameElement.src; // 获取当前窗口所在的iframe的src属性
        var scrollPosition = sessionStorage.getItem('scrollPosition_' + frameSrc);
        console.log('scrollTop：' + scrollPosition)
        if (scrollPosition !== null) {
            $(window.frameElement).contents().find('.fixed-thead-body').scrollTop(scrollPosition);
        }
    }
}

/**
 * 表格宽度调整
 */
function loadTableTool() {
    let isdown = false, beginx = 0, oldwidth = 0, parent
    const has = $(document).find('.fixed-thead').length
    const obj = (has === 1) ? ".fixed-thead-head > .tableMany > thead > tr" : ".tableMany > thead > tr"
    // 鼠标抬起
    $(document).mouseup(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target)) {
                isdown = false
                const field = $(parent).attr('sort-key'),
                    width = !isNaN($(parent).attr('width')) ? $(parent).attr('width') : 80
                // let string = $("[name='listForm']").serialize()
                let pageStr = $(parent).parents('.tableMany').eq(0).data('page');
                let string = 'sourceClick=colWidth&page=' + pageStr;
                //显示的字段
                $(parent).parents('.tableMany').eq(0).find("td[sort-key]").each(function () {
                    string += '&fields[]=' + $(this).attr('sort-key')
                })
                if (field && width !== oldwidth && !isNaN(width) && !isEmpty(pageStr)) {
                    // if (string.indexOf('fields') < 0) {
                    //     msg('请先设置需显示的列', 'error')
                    // } else {
                    if (parseFloat(oldwidth) === parseFloat(width)) {
                        return false
                    }
                    string += '&' + field + '=' + parseFloat(width)
                    $.post(root + 'control/adIndex.html?cla=homepage&fun=setField', string, function (res) {
                        if (res.code === 0) {
                            msg(res.warn, 'error')
                        }
                    }, 'json')
                    // }
                }
            }
        }
    })
    // 鼠标点击
    $(document).mousedown(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target)) {
                isdown = true
                beginx = parseFloat(that.pageX)
                parent = that.target.offsetParent
                oldwidth = parseFloat($(parent).attr('width') ? $(parent).attr('width') : parent.clientWidth)
            }
        }
    })
    // 鼠标移动
    $(document).mousemove(function (that) {
        if ($(obj).length > 0) {
            if (($.contains($(obj)[0], that.target) || $(obj)[0] === that.target) && isdown) {
                const fixedObj = $(document).find('.fixed-thead > .fixed-thead-body > table')
                parent.width = oldwidth + parseFloat(that.pageX) - beginx
                if (fixedObj.length === 1) {
                    $(document).find("[sort-key='" + $(parent).attr('sort-key') + "']").last().width(oldwidth + parseFloat(that.pageX) - beginx)
                }
            } else {
                isdown = false
            }
        }
    })
}

//点击左侧导航
function iframeHref(obj) {
    //赋值
    var url = $(obj).attr("iframeHref");
    var name = $(obj).attr("title");
    var titleName = $("[iframeMenuName='" + name + "']").html();
    var menuOne = $(obj).data('one'); //一级菜单
    var menuTwo = $(obj).data('two'); //二级菜单
    //检查此页卡是否存在
    if (titleName) {
        iframeTitle(titleName);
    } else {
        //添加iframe
        $("[iframeName]").css("display", "none");
        $("#frameRight").append(`<iframe scrolling='yes' frameborder='0' class='iframe' iframeName='${name}' src='${url}'></iframe>`);
        //延长ul
        $("#iframeTitle > ul").css({
            width: "+=137px"
        });
        //添加顶部页卡
        $("#homepage").removeClass("iframeTitleNow");
        $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
        var widthTitle = parseFloat($("#iframeTitle").css("width"));
        var bigNum = parseInt(widthTitle / 137) - 2;
        var length = $("#iframeTitle > ul > li").length;
        var iframeTitleNow = `<li class="iframeTitleNow"><div title="${name}" iframe_menu_one="${menuOne}" iframe_menu_two="${menuTwo}" iframeMenuName="${name}" goback="${name}">${name}</div><div class="iframeClose" onclick="iframeClose(this)">×</div></li>`;
        if (length > bigNum) {
            $("#iframeTitle > ul > li:eq(" + bigNum + ")").after(iframeTitleNow);
        } else {
            $("#iframeTitle > ul").append(iframeTitleNow);
        }
        //修正左侧翻页箭头
        var widthUl = parseFloat($("#iframeTitle > ul").css("width"));
        var left = parseFloat($("#iframeTitle > ul").css("left"));
        if (widthUl + left > widthTitle) {
            $("#pageRight > img").attr("src", root + "img/control/pageRightLight.svg");
        }
    }
    //高亮显示左侧当前导航
    // $("[iframeHref]").removeClass("frameLeftHover");
    $(obj).addClass("frameLeftHover");
    $("[menuParent='" + menuOne + "']").removeClass("frameLeftShow");
    $("li[menu_one='" + menuOne + "'][menutwo='" + menuTwo + "']").addClass("frameLeftShow");
    removeHover();
    hideMenuFour();
}

// 关闭页卡
function iframeClose(obj) {
    var name = $(obj).prev().html();
    var goBack = $("[iframeName='" + name + "']").attr('goback'); //检查是否存在高亮的顶部页卡
    // 缩短ul
    $("#iframeTitle > ul").css({
        width: "-=137px"
    });
    // 多个iframe删除
    $("[goback='" + name + "']").remove();
    $("[iframeName='" + name + "']").remove();
    $(obj).parent().remove(); //删除顶部页卡
    // 判断上级是否存在
    if (goBack) {
        iframeTitle(goBack, 'top')
    } else {
        if($('#iframeTitle').find('.iframeTitleNow').length === 0) {
            $("[iframeName=主页]").css("display", "block"); //显示我的桌面iframe
            $("#homepage").addClass("iframeTitleNow"); //高亮我的桌面顶部页卡
            $("[iframeHref]").removeClass("frameLeftHover"); //清理左侧导航高亮选择效果
        }
    }
    //修正右侧翻页箭头
    fixRightArrow()
}

//修正右侧翻页箭头
function fixRightArrow() {
    var _$ = window.top.$
    var widthTitle = parseFloat(_$("#iframeTitle").css("width"));
    var widthUl = parseFloat(_$("#iframeTitle > ul").css("width"));
    var left = parseFloat(_$("#iframeTitle > ul").css("left"));
    if (widthUl + left <= widthTitle) {
        _$("#pageRight > img").attr("src", root + "img/control/pageRight.svg");
    }
}

// 关闭当前悬浮页面
function iframeReturnClose(obj, name) {
    //赋值
    var detail = $('#detail', window.parent.document);
    //关闭当前页面，刷新父级页面
    //如果是列表页，则保留查询条件和分页
    var $parentIframe = $(window.parent.frameElement)
    var $iframeContent = $parentIframe.contents();
    log($iframeContent.find("[searchformhtml]").length)
    if ($iframeContent.find("[searchformhtml]").length > 0) {
        //更新查询结果
        var pageNow = $iframeContent.find("[searchformhtml] .pageButton .pageNow");//当前页
        if (pageNow.length === 1) {//如果存在分页
            pageNow.click();
        } else {
            $iframeContent.find("[searchformhtml]").find("input[type=submit]").click();
        }
        // 在这里执行需要等待异步请求结束后的代码，函数将会被执行一次，之后就会被销毁
        $(document).one('ajaxStop', function () {
            initScrollPosition();
        });
    }
    /*else if ($iframeContent.find("#renovate").attr("url")) {
        $parentIframe.attr("src", $iframeContent.find("#renovate").attr("url")+'&a=1');
    }*/
    //操作
    detail.empty();//清空详情页，防止详情页存在自动程序时消耗服务器和浏览器资源
    detail.hide();//隐藏详情页

    /*
    var _$ = window.top.$
    // 关闭当前页，回到上层页
    var iframe = _$("[iframeName='" + name + "']")
    var goBack = iframe.attr('goback'); //上级页面
    var liObj = _$("#iframeTitle").find('.iframeTitleNow').find('[iframemenuname]')
    liObj.attr('goback', liObj.attr('iframemenuname'))
    // 移除 选项卡 移除页面
    iframe.remove()
    _$("#frameRight [goback='" + goBack + "']").remove();
    // liObj.remove()
    // 回到上级页面
    if (goBack.length > 0) {
        // _$("[iframeName='" + goBack + "']").css("display", "block");
        // let beforeFrame = _$("#frameRight [goback='" + goBack + "']");
        // console.log(beforeFrame)
        // if (beforeFrame.length >0){
        //     beforeFrame.css("display", "block");
        // }else{
        //     console.log('列表')
        //
        // }
        _$("[iframeName='" + goBack + "']").css("display", "block");
    } else {
        _$("[iframeName=主页]").css("display", "block"); //显示我的桌面iframe
        _$("#homepage").addClass("iframeTitleNow"); //高亮我的桌面顶部页卡
        _$("[iframeHref]").removeClass("frameLeftHover"); //清理左侧导航高亮选择效果
    }
    //修正右侧翻页箭头
    fixRightArrow()
     */
}

function cls() {
    console.clear()
}

function log(obj) {
    console.log(obj)
}

//页卡切换函数
function iframeTitle(name, posititon = null) {
    //iframe切换
    $("[iframeName]").css("display", "none");
    $("[iframeName='" + name + "']").css("display", "block");
    //顶部页卡切换
    $("#homepage").removeClass("iframeTitleNow");
    $("#iframeTitle > ul > li").removeClass("iframeTitleNow");
    if (posititon != 'top') {
        $("[iframeMenuName='" + name + "']").parent().addClass("iframeTitleNow");
    } else {
        $("[goback='" + name + "']").parent().addClass("iframeTitleNow");
        // 菜单跟踪
        //顶部切换时
        let iframemenuname = $("[iframemenuname='" + name + "']");
        let iframe_menu_one = iframemenuname.attr('iframe_menu_one');
        let menuTwo = iframemenuname.attr('iframe_menu_two');
        let left_three_menu = $("li[menu_one='" + iframe_menu_one + "'][menutwo='" + menuTwo + "']"); //三级菜单对象
        let display = left_three_menu.css('display');
        if (!display) {
            if (iframe_menu_one !== undefined && iframe_menu_one) {
                //left_three_menu = $("li[menutwo='" + menuTwo + "'][title='" + menuTwo + "']"); //三级菜单对象
                //二级菜单滑动
                // $("[menuParent=" + menuOne + "]").slideToggle();
                // display = left_three_menu.css('display');
                let obj = $("li[menuone='" + iframe_menu_one + "']"); //二级菜单对象
                menuOne(obj);
            }
        } else {
            //都在当前一级菜单中
            if (display === 'none') {
                //二级菜单滑动
                // $("[menuParent=" + menuOne + "]").slideToggle();
                let obj = $("li[menuone='" + iframe_menu_one + "']"); //二级菜单对象
                menuOne(obj);
            }
        }
        if(iframe_menu_one) {
            $("[menuParent='" + iframe_menu_one + "']").removeClass("frameLeftShow");
            left_three_menu.addClass("frameLeftShow");
        }
    }
}


//左侧菜单点击事件~一级菜单
function menuOne(obj) {
    //重置箭头和菜单
    $("[menuParent]").slideUp();
    $("[menuone]").children("img").attr("src", root + "img/images/triangleRight.png");
    //二级菜单滑动
    let menuTwo = $("[menuParent='" + $(obj).attr("menuOne") + "']");
    if (menuTwo.css('display') === "none") {
        menuTwo.slideDown();
        $(obj).children("img").attr("src", root + "img/images/triangleDown.png");
    }
}

/**
 * 生成随机id,默认16位
 * @param length
 * @returns {string}
 */
function getId(length = 15) {
    var charset = 'abcdefghijklmnopqrstuvwxyz0123456789';
    var result = '';
    for (var i = 0; i < length; i++) {
        var randomIndex = Math.floor(Math.random() * charset.length);
        result += charset.charAt(randomIndex);
    }
    return 'a' + result;
}

/**
 * 替换链接参数
 * @param url
 * @param paramName
 * @param paramValue
 * @returns {*|string}
 */
function replaceUrlParam(url, paramName, paramValue) {
    var pattern = new RegExp('(' + paramName + '=).*?(&|$)');
    if (url.search(pattern) >= 0) {
        return url.replace(pattern, '$1' + paramValue + '$2');
    }
    return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
}

/*
 * iframe中新增顶层页卡
 *
 * 目的：系统中点击某些按钮时需要保留当前页面状态，并打开一个新的页面呈现用户需求。
 * 方法：触发本函数时，系统在adIndex.php创建一个新的iframe，即页卡。
 * 参数：name为顶层页卡名称，url为页卡的路径。
 */
function newIframe(name, url, iframe_menu_one = '', iframe_menu_two = '', open = false) {
    var parentDocument = window.parent.document
    var goBack = $(parentDocument).find('.iframeTitleNow > div').html() ? $(parentDocument).find('.iframeTitleNow > div').html() : '主页'
    //var homepage = $('#homepage', window.top.document).hasClass('iframeTitleNow')  //判断当前是否在首页，在首页则打开新的页卡
    if (name === "") {
        warn("在iframe中新增顶层iframe时name为空");
        return false
    } else if (url === "") {
        warn("在iframe中新增顶层iframe时url为空");
        return false
    } else {
        //判断当前是否在iframe中
        if (window.top === window.self || open) {
            let short_url = url.substring(0, url.indexOf("&fun"));
            let iframeObj = $("[iframename='" + name + "']", parentDocument);
            var titleName = iframeObj.attr('iframename');
            if (titleName === name) {
                $("[iframeName='" + name + "']", parentDocument).attr("src", url);
                //iframe切换
                $("[iframeName]", parentDocument).css("display", "none");
                iframeObj.css("display", "block");
                $("#iframeTitle > ul > li", parentDocument).removeClass("iframeTitleNow");

                //顶部导航栏选中状态
                let iframemenuname = name;
                let backName = iframeObj.attr('goback');
                if (backName && backName !== 'undefined') {
                    iframemenuname = backName;
                }
                let topTab = $("[iframemenuname='" + iframemenuname + "']", parentDocument);
                if (topTab.length > 0) {
                    topTab.parent("li").addClass("iframeTitleNow");
                }
            } else {
                let iframename = $('.iframeTitleNow', parentDocument).children('[iframemenuname]').attr('iframemenuname');
                let urlNow = $("iframe[iframename='" + iframename + "']", parentDocument).attr('src');
                if (urlNow) {
                    urlNow = urlNow.substring(0, urlNow.indexOf('&fun'))
                }
                // 判断是否携带ID参数，如携带且是新增则打开后替换
                if (name.indexOf('新') > -1 || name.indexOf('New') > -1) {
                    url = replaceUrlParam(url, 'id', getId(15))
                }

                if (short_url === urlNow) {
                    //如果需要跳转的类跟当前打开页卡的类一致，则在当前页打开，否则另开页卡
                    // 共用上级页面名称 ，先隐藏所有上级页面
                    $("[iframeName]", parentDocument).css("display", "none");
                    $("#frameRight", parentDocument).append(`<iframe scrolling="yes" frameborder="0" class="iframe" iframeName="${name}" src="${url}" goback="${goBack}" onload="iframeLoaded(this, '${name}')"></iframe>`);
                } else {
                    //添加iframe
                    $("[iframeName]", parentDocument).css("display", "none");
                    $("#frameRight", parentDocument).append("<iframe scrolling='yes' frameborder='0' class='iframe'   iframeName='" + name + "' src='" + url + "'></iframe>");
                    //延长ul
                    $("#iframeTitle > ul", parentDocument).css({width: "+=137px"});
                    //添加顶部页卡
                    $("#homepage", parentDocument).removeClass("iframeTitleNow");
                    $("#iframeTitle > ul > li", parentDocument).removeClass("iframeTitleNow");
                    var widthTitle = parseFloat($("#iframeTitle", parentDocument).css("width"));
                    var bigNum = parseInt(widthTitle / 137) - 2;
                    var length = $("#iframeTitle > ul > li", parentDocument).length;
                    var iframeTitleNow = "<li class='iframeTitleNow'><div title='" + name + "' iframe_menu_one='" + iframe_menu_one + "' iframe_menu_two='" + iframe_menu_two + "'  iframeMenuName='" + name + "' >" + name + "</div><div class='iframeClose' onclick=\"iframeClose(this)\">×</div></li>";
                    if (length > bigNum) {
                        $("#iframeTitle > ul > li:eq(" + bigNum + ")", parentDocument).after(iframeTitleNow);
                    } else {
                        $("#iframeTitle > ul", parentDocument).append(iframeTitleNow);
                    }
                }

            }

            $('.iframeTitleNow', parentDocument).children('[iframemenuname]').attr('goback', name)

            //切换左侧导航
            var src = $("[iframeName='" + name + "']", parentDocument).attr("src");
            $("[iframeHref]", parentDocument).removeClass("frameLeftHover");
            $("[iframeHref='" + src + "']", parentDocument).addClass("frameLeftHover");
            if (iframe_menu_one && iframe_menu_two) {
                //切换页卡
                iframeTitle(name, 'top');
            }
        } else {
            //创建载体
            if ($("#detail").length === 0) {
                $("#body").append("<div id='detail'></div>");
            } else {
                $("#detail").css("display", "block");
            }
            //重新载入iframe
            $("#detail").html(`<iframe scrolling="yes" frameborder="0" class="iframe" iframeName="${name}" src="${url}" goback="${goBack}" onload="iframeLoaded(this, '${name}')"></iframe>`);
        }
    }
}

// 刷新当前Iframe
function refreshNowIframe(url='') {
    if(url === ''){
        url = $(window.frameElement).attr('src')
    }
    $(window.frameElement).attr('src', url)
}

// 动态加载
function iframeLoaded(obj, name) {
    let returnHtml = `<div id="close" onclick="iframeReturnClose(this, '${name}')"><img title="关闭" src="${root}img/control/close.svg" iframeName="${name}"></div>`
    let body = $(obj).contents()
    let ele = body.find("#header").find('#renovate')
    if (ele.length > 0) {
        ele.before(returnHtml)
        body.find('#renovate, .onion').css('left', '+=40')
    }
}


/*顶部导航位置挪动*/
function moveMenu() {
    //初始化
    var div = "#iframeTitle > ul > li > div:first-of-type"; //点击区域
    var li = "#iframeTitle > ul > li"; //移动区域
    //按下鼠标
    $(document).on("mousedown", div, function (e) {
        //参数准备
        var ev = e || event;
        var startX = ev.clientX; //鼠标初始横坐标
        var thisli = $(this).parent(); //选中的li标签
        var width = thisli.outerWidth(true); //包含margin，border，padding的li标签宽度
        var length = $(li).length; //li标签的数量
        var index = thisli.index();
        var left = width * index; //此li标签的左侧间距，也是占位空白标签初始位置
        var name = $(this).attr("goback");
        //切换页卡
        iframeTitle(name, 'top');
        //切换左侧导航
        var src = $("[iframeName='" + name + "']").attr("src");
        $("[iframeHref]").removeClass("frameLeftHover");
        $("[iframeHref='" + src + "']").addClass("frameLeftHover");
        //占位空白标签效果
        $("<li class='empty'></li>").insertBefore(thisli);
        //将选中的li标签放在最后，方便insertBefore
        thisli.insertAfter(li + ":eq(" + length + ")");
        //将选中的li标签悬浮，方便跟随鼠标挪动
        thisli.css({
            "position": "absolute", "top": "0", "left": left
        });
        //鼠标移动
        document.onmousemove = function (m) {
            //获取参数
            var mv = m || event;
            var endX = mv.clientX; //当前鼠标横坐标
            //计算值
            var moveX = endX - startX; //鼠标按下后移动的距离
            var winLeft = left + moveX; //移动后此li标签的左侧距离
            //菜单移动效果
            thisli.css({
                "left": winLeft + "px"
            });
            //占位空白标签挪动
            if (winLeft < 0) {
                var newIndex = 0;
            } else {
                var newIndex = parseInt(winLeft / width) + 1;
            }
            $(li + ".empty").insertBefore(li + ":eq(" + newIndex + ")");
            // console.log(
            //     "startX:" + startX +
            //     ";width:" + width +
            //     ";length:" + length +
            //     ";index:" + index +
            //     ";left:" + left +
            //     ";name:" + name +
            //     ";startX:" + startX +
            //     ";endX:" + endX +
            //     ";moveX:" + moveX +
            //     ";winLeft:" + winLeft +
            //     ";newIndex:" + newIndex
            // );
        }
        //鼠标释放
        document.onmouseout = document.onmouseup = function () {
            //菜单最终位置
            $(thisli).insertBefore(li + ".empty");
            //清理移动效果
            $(li).css({
                "position": "", "top": "", "left": ""
            });
            //清理占位空白标签
            $(li + ".empty").remove();
            //清理事件
            document.onmousemove = null;
            document.onmouseup = null;
            document.onmouseout = null;
        }
    });
}

//把数字金额转换成中文大写数字
function upperMoney(money) {
    var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]; //汉字的数字
    var cnIntRadice = ["", "拾", "佰", "仟"]; //基本单位
    var cnIntUnits = ["", "万", "亿", "兆"]; //对应整数部分扩展单位
    var cnDecUnits = ["角", "分", "毫", "厘"]; //对应小数部分单位
    var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字
    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义
    var Symbol = "";//正负值标记
    var i = 0;
    if (money === "") {
        return "";
    }
    money = parseFloat(money);
    if (money >= maxNum) {
        msg('超出最大处理数字', 'error');
        return "";
    }
    if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        return ChineseStr;
    }
    if (money < 0) {
        money = -money;
        Symbol = "负 ";
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (i; i < IntLen; i++) {
            var n = IntegerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; //归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
    }
    if (DecimalNum != '') { //小数部分
        var decLen = DecimalNum.length;
        i = 0;
        for (i; i < decLen; i++) {
            var n = DecimalNum.substr(i, 1);
            if (n != '0') {
                ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (ChineseStr == '') {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (DecimalNum == '') {
        ChineseStr += cnInteger;
    }
    ChineseStr = Symbol + ChineseStr;

    return ChineseStr;
}

/***详情页选项卡切换***/
function detailTab(cla, fun, id, pageType = null) {
    //更新当前页面URL
    $("#renovate").attr("url", getEdit("menu", fun));
    //切换导航
    $("#pageMenu > ul > li").removeClass("pageMenuHover");
    $("[pageMenu=" + fun + "]").addClass("pageMenuHover");
    //切换内容页
    $("[pagediv]").hide();
    if ($("[pagediv=" + fun + "]").length >= 1) {
        $("[pagediv=" + fun + "]").show();
        // 表格固定，切换需要重新渲染固定行，不然样式会出问题
        if ($('.tableMany').length >= 1 && $('.fixed-thead').length >= 1) {
            const obj = $('.tableMany')
            obj.fixedThead.option = {fixed: true}
            obj.fixedThead()
        }
    } else {
        if (cla === 'scheduler') {
            let date = GetQueryString('date');
            if (date) {
                id += '&date=' + date;
            }
        }
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&id=" + id, function (data) {
            if (data.warn) {
                warn(data.warn);
            } else if ($("[pagediv=" + fun + "]").length >= 1) { //防止后台推送多次数据
                $("[pagediv=" + fun + "]").html(data.html);
            } else {
                // if (pageType === 'list'){
                $("#pageMenu").after("<div class='pageDiv' pageDiv='" + fun + "'>" + data.html + "</div>");
                // }else{
                //     $("#pageMenu").after("<div class='pageDiv' pageDiv='" + fun + "'><div class='tab-box'><div class='tab-content'>" + data.html + "</div></div></div>");
                // }

            }
        }, "json");
    }
}

/*刷新当前页面*/
function reloadPage(obj) {
    window.location.href = $(obj).attr("url");
}

/*修改GET参数*/
function getEdit(key, value) {
    //获取当前页面URL
    var oldUrl = document.location.href;
    //获取GET参数
    var one = oldUrl.split("?");
    var get = one[1];
    var para = get.split("&");
    //拼接不需要修改的GET参数
    var newUrl = one[0] + "?";
    for (var i = 0; i < para.length; i++) {
        if (para[i].indexOf(key + "=") == -1) {
            newUrl += para[i] + "&";
        }
    }
    //添加要修改的参数
    newUrl += key + "=" + value;
    //返回
    return newUrl;
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/***列表页提交查询按钮***/
function searchFormSub(cla, fun) {
    let array = ["multiColumnAccount",'initialization'];
    if (array.indexOf(cla) !== -1){
        searchForm(cla, fun, 1,true,{fixed:false});
    }else{
        searchForm(cla, fun, 1);
    }
    return false;
}

/**
 * 列表数据查询函数
 * @param cla 类名
 * @param fun 方法
 * @param page 页码
 * @param formData 是否表单
 * @param option 表头固定参数 fixed 是否表头固定 height 固定高  col 需要固定地列数
 * 不需要表头固定使用 ，请在 searchForm 函数执行完后加入 $('#tableid').fixedThead('destroy')
 */
function searchForm(cla, fun, page, formData = true, option = {fixed: true}) {
    $("#" + fun + "Html").html("数据查询中，请稍后。。。");
    let params = (formData === true) ? $("[name=" + fun + "Form]").serialize() : formData
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&page=" + page, params, function (data) {
        if (data.warn) {
            warn(data.warn);
        } else {
            $("#" + fun + "Html").html(data.html)
            if (option.fixed && $("#" + fun + "Html").find('table').length > 0) {
                let tableId = getId()
                $("#" + fun + "Html").find('table').attr('id',tableId)
                // 表格固定
                const obj = $('#'+tableId)
                obj.fixedThead.option = option
                obj.fixedThead()

                // 延迟一段时间，等待 fixedThead 创建完成
                setTimeout(function () {
                    // 绑定滚动监听器
                    $('.fixed-thead-body').scroll(function () {
                        // 保存滚动位置
                        var frameSrc = window.frameElement.src; // 获取当前窗口所在的iframe的src属性，确保每个 iframe 使用独立的存储区域
                        var scrollPosition = $(this).scrollTop();
                        if (scrollPosition !== 0) {
                            sessionStorage.setItem('scrollPosition_' + frameSrc, scrollPosition);
                        }
                    });
                }, 100);
            }
        }
        // 加载表格方法
        loadTableTool()
    }, "json");
}

/*表格行点击标记*/
function tableManyClick(obj) {
    $(obj).siblings().removeClass("tableManyClick");
    $(obj).addClass("tableManyClick");
}

/***调取弹出层***/
function layer(cla, fun, json) {
    // let con = setTimeout(function () {
    //     $("#loading", window.top.document).hide();
    // }, js_configurg.loading_time_out);
    // $("#loading", window.top.document).show();
    var searchFormId = $(event.target).parents("[searchformhtml]").attr("searchformhtml");
    var layerId = '';
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, json, function (data) {
        // $("#loading", window.top.document).hide();
        // clearTimeout(con);
        data.searchFormId = searchFormId;
        layerId = data.id
        data.obj = event.target;//发生点击事件的当前html节点
        data.isIframe = window.top !== window.self
        data.currentIframe = window.frameElement; // 当前 iframe
        layerFun(data);
    }, "json");
    // 异步处理完后，根据文本域内容加载高度
    $(document).one('ajaxStop', function () {
        textareaHeightHandle($('.layerList'))
        //layerSearchHeightHandle(layerId)
    });
    // 阻止事件冒泡
    var e = event || window.event;
    e.stopPropagation();
    return false;
}

/***警示弹出层函数***/
function pasWarn(formName, cla, fun) {
    var searchFormId = $(event.target).parent().attr("searchformhtml");
    $.post(root + 'control/adIndex.html?cla=pasWarn', {
        formName: formName, cla: cla, fun: fun
    }, function (data) {
        data.searchFormId = searchFormId;
        layerFun(data);
    }, 'json');
}

/***弹出层返回函数***/
function layerFun(data) {
    if (data.warn) {
        returnProcess(data)
    } else {
        var id = $("#" + data.id);
        if (id.length == 0) {
            var searchFormId = "";
            if (typeof data.searchFormId != "undefined") {
                searchFormId = " searchFormId='" + data.searchFormId + "' ";
            }
            $("#body").append("<div id='" + data.id + "' layerId='" + data.id + "' " + searchFormId + ">" + data.html + "</div>");
        } else {
            id.html(data.html);
            id.css("display", "block");
        }
        move(data.id);
    }
}

/***文件上传函数***/
function icoFun(formName, id) {
    var form = eval('document.' + formName);
    form.id.value = id;
    form.file.click();
}

/***项目管理-我的任务-项目网页-以文件形式更新网页***/
function projectPageUpdate(projectPageId) {
    var form = document.pageUpdateForm;
    form.projectPageId.value = projectPageId;
    form.file.click();
}

/***生成密码***/
function getPas() {
    var num = "";
    for (var i = 0; i < 6; i++) {
        num += Math.floor(Math.random() * 10);
    }
    document.staffForm.password.value = num;
}

/***主页-修改密码-发送手机短信验证码***/
function pasSms() {
    $.post(root + "control/adIndex.html?cla=my&fun=pasSms", function (data) {
        warn(data.warn);
    }, "json");
}

/***忘记密码-根据登录用户名发送手机短信验证码-登录时使用***/
function pas(name) {
    $.post(root + "library/libData.html?type=adForgetPassword", {
        name: name
    }, function (data) {
        warn(data.warn);
    }, "json");
}

/***全选***/
function checkAll(obj) {
    var formName = $(obj).attr("form");
    var checkName = $(obj).attr("name");
    var form = $(obj).closest("[name='" + formName + "']");
    var bool = $(obj).prop("checked");

    let isFixed = false;
    form.children().each(function () {
        if ($(this).hasClass('fixed-thead')) {
            isFixed = true;
        }
    });

    if (isFixed) {
        form.find(".fixed-thead-body [name='" + checkName + "\\[\\]']").prop('checked', bool);
    } else {
        console.log(bool)
        form.find("[name='" + checkName + "\\[\\]']").prop('checked', bool);
    }
}

/*全选本区域权限*/
function powerCheckAll(obj) {
    var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parents(".box").find(":checkbox").prop('checked', bool);
}

//php的checkbox函数自带js
function checkboxAll(obj) {
    var name = $(obj).val();
    let bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parent().siblings("label").children("[name='" + name + "\[\]']").prop('checked', bool);
}


/*将下拉菜单赋值到下一个输入框*/
function selectGetText(obj) {
    $(obj).next().val(obj.value);
}

/***人力资源管理 - 行政人事 - 职位管理 根据一级导航查询二级导航***/
function getPowerTwo(obj, name = 'powerTwo', value = '') {
    var val = obj.value;
    $.post(root + "control/adIndex.html?cla=role&fun=getPowerName", {
        name: val, value: value
    }, function (data) {
        $(obj).closest('form').find('[name="' + name + '"]').html(data.res);
    }, "json");
}

function getPowerThree(obj, name = 'powerThree', oneName = 'powerOne', field = 'name', value = '') {
    var val = obj.value, one = $(obj).closest('form').find('[name="' + oneName + '"]').val();
    $.post(root + "control/adIndex.html?cla=role&fun=getPowerName", {
        name: one + '-' + val, level: 2, field: field, value: value
    }, function (data) {
        $(obj).closest('form').find('[name="' + name + '"]').html(data.res);
    }, "json");
}

function getPowerFour(obj, name = 'powerFour', oneName = 'powerOne', twoName = 'powerTwo', field = 'name', value = '') {
    var val = obj.value, one = $(obj).closest('form').find('[name="' + oneName + '"]').val();
    let two = $(obj).closest('form').find('[name="' + twoName + '"]').val();
    $.post(root + "control/adIndex.html?cla=role&fun=getPowerName", {
        name: one + '-' + two + '-' + val, level: 3, field: field, value: value
    }, function (data) {
        $(obj).closest('form').find('[name="' + name + '"]').html(data.res);
    }, "json");
}

/*行政人事-根据分类加载部门*/
function getDeparment(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getDeparment", {
        type: obj.value
    }, function (data) {
        //本分类下部门选项
        var departmentId = $(obj).next("select");
        if (departmentId.attr("title") == "当前部门") {
            departmentId.html(data.departmentId);
        }
        //本部门下职位
        var jobId = $(obj).nextAll("select").eq(1);
        if (jobId.attr("title") == "当前职位") {
            jobId.html("<option value=''>-当前职位-</option>");
        }
        //本职位下员工
        var staffId = $(obj).nextAll("select").eq(2);
        if (staffId.attr("title") == "员工") {
            staffId.html("<option value=''>-员工-</option>");
        }

    }, "json");
}

/*行政人事-根据部门ID加载职位*/
function getJob(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getJob", {
        deparmentId: obj.value
    }, function (data) {
        //本部门下职位
        var jobId = $(obj).next("select[name='jobId']");
        jobId.html(data.jobId);
        //本职位下员工
        var staffId = $(obj).nextAll("select").eq(1);
        staffId.html("<option value=''>-员工-</option>");

    }, "json");
}

/*行政人事-根据职位ID加载员工*/
function getStaff(obj) {
    $.post(root + "control/adIndex.html?cla=staff&fun=getStaff", {
        jobId: obj.value
    }, function (data) {
        var stid = $(obj).next("select");
        stid.html(data.stid);
    }, "json");
}

/***行政人事-员工管理-社保扣款-汇总员工结算账户***/
function lastMoneyCutAll() {
    var moneyAll = 0;
    $("[name=lastMoneyCutForm] [name=lastMoneyCut]").each(function () {
        var money = parseFloat($(this).val());
        moneyAll += money;
    });
    $("#lastMoneyCutAllId").text("￥" + moneyAll.toFixed(2));
}

/***行政人事-员工管理-社保扣款-提交***/
function lastMoneyCutFormSub() {
    //获取员工和扣款关联数组
    var lastMoneyCut = {};
    $("[name=lastMoneyCutForm] [name=lastMoneyCut]").each(function () {
        var key = $(this).attr("stid");
        lastMoneyCut[key] = $(this).val();
    });
    //整理json数组
    var postData = {
        "lastMoneyCut": lastMoneyCut
    };
    //提交
    $.post(root + "control/adIndex.html?cla=settlementAccounts&fun=lastMoneyCutFormSub", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*员工选择器-搜索员工*/
function staffChoice(obj) {
    var quit = "no";
    if ($("#staffQuit").hasClass("staffQuitChoice")) {
        quit = "yes";
    }
    staffSearch({
        name: $(obj).val(), quit: quit
    });
}

/*员工选择器-初始化*/
function staffChoiceClear() {
    $("#staffChoiceSearch").val("");
    staffSearch({
        name: ""
    });
}

/*员工选择器-根据职位查询员工*/
function staffChoiceDepartment(departmentId) {
    staffSearch({
        departmentId: departmentId
    });
}

/*员工选择器-显示离职员工*/
function staffQuit(obj) {
    //切换离职按钮效果
    $(obj).toggleClass("staffQuitChoice");
    //如果查询框有值，则重新查询
    var staffChoiceSearch = $("#staffChoiceSearch").val();
    if (staffChoiceSearch != "") {
        if ($("#staffQuit").hasClass("staffQuitChoice")) {
            var quit = "yes";
        } else {
            var quit = "no";
        }
        staffSearch({
            name: staffChoiceSearch, quit: quit
        });
    }
}

/*员工选择器-异步获取员工列表*/
function staffSearch(json) {
    $.post(root + "control/adIndex.html?cla=examine&fun=staffChoiceSearch", json, function (data) {
        $("#staffChoiceResult").html(data.html);
    }, "json");
}

/*员工选择器-选择员工*/
function staffClick(stid, name, src) {
    if ($("[examineStaff='" + stid + "']").length > 0) {
        warn("此审批人已经存在");
    } else {
        $('#examineStaffChoice').hide();
        $("#staffAdd").before("<div examineStaff='" + stid + "'><img src='" + src + "'><div onclick='staffChoiceDel(this)'>×</div><div>" + name + "</div><img src='" + root + "img/images/link.png'></div>");
    }
}

function staffChoiceDel(obj) {
    $(obj).parent().remove();
}

/*行政人事-工作事务-编辑页面-提交*/
function examineSub() {
    //获取审核人
    var staffId = new [];
    $("[examineStaff]").each(function () {
        staffId.push($(this).attr("examineStaff"));
    });
    //整理json数组
    var postData = {
        "target": document.examineDetail.target.value,
        "jobId": document.examineDetail.jobId.value,
        "list": document.examineDetail.list.value,
        "text": document.examineDetail.text.value,
        "id": document.examineDetail.id.value,
        "staffId": staffId,
    };
    //提交
    $.post(root + "control/adIndex.html?cla=examine&fun=examineSub", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/***行政人事-工作日-选择工作日***/
function squareLiChoice(obj) {
    var squareLi = $(obj).attr("squareLi");
    if (squareLi == "no") {
        $(obj).attr("squareLi", "yes");
    } else if (squareLi == "yes") {
        $(obj).attr("squareLi", "no");
    }
}

/***行政人事-工作日-提交工作日***/
function workDaySub(obj) {
    var workDay = new [];
    $("[squareLi=yes]").each(function () {
        workDay.push($(this).attr("workDayLiNum"));
    });
    var postData = {
        "moon": document.detailForm.moon.value,
        "text": document.detailForm.text.value,
        "id": document.detailForm.id.value,
        "workDay": workDay
    };
    $.post(root + "control/adIndex.html?cla=workDay&fun=detailEdit", postData, function (data) {
        if (data.warn == 2) {
            window.location.href = data.href;
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*行政人事-提交加班成果报告-根据关键词获取加班对象*/
function workAddFruitShow(obj) {
    $(obj).siblings(".asynchronousMenu").show();
    workAddFruitKey(obj);
}

function workAddFruitKey(obj) {
    var target = document.workAddFruitForm.target.value; //加班对象
    var key = document.workAddFruitForm.targetId.value; //关键词
    $.post(root + "control/adIndex.html?cla=workAdd&fun=fruitKey", {
        target: target, key: key
    }, function (data) {
        $(obj).siblings(".asynchronousMenu").children("ul").html(data.html);
    }, "json");
}

function workAddFruitName(obj) {
    var name = $(obj).html();
    var targetId = $(obj).attr("fruitTargetId");
    var input = $(obj).parents(".asynchronousMenu").siblings("[name=targetId]");
    input.val(name);
    input.attr("targetId", targetId);
}

function workAddFruitHide(obj) {
    $(obj).siblings(".asynchronousMenu").hide();
}

/*行政人事-提交加班成果报告-添加加班成果*/
function workAddFruitSub() {
    //组合tr
    var form = document.workAddFruitForm;
    var target = form.target.value;
    var targetId = form.targetId.getAttribute("targetId");
    var targetName = $("[fruitTargetId='" + targetId + "']").text();
    var hour = form.hour.value;
    var text = form.text.value;
    var fruitId = form.fruitId.value;
    var button = "<span fruitId='" + fruitId + "' target='" + target + "' targetId='" + targetId + "' hour='" + hour + "' text='" + text + "' onclick=\"workAddFruitEdit(this)\" class='spanButton'>编辑</span>" + "\n<span onclick=\"workAddFruitDel(this)\" class='spanButton'>删除</span>";
    var checkTarget = $("#workAddFruitTable").find("[targetId='" + targetId + "']");
    var checkTr = $("#workAddFruitTable").find("[fruitId='" + fruitId + "']");
    var checkPrice = /^[0-9]+(.[0-9]{1,2})?$/;
    if (target == "") {
        warn("请选择加班对象");
    } else if (form.targetId.value == "") {
        warn("请选择对象名称");
    } else if (targetName == "") {
        warn("未找到此对象名称");
    } else if (hour == "") {
        warn("请输入加班小时数");
    } else if (!checkPrice.test(hour)) {
        warn("加班小时数格式有误");
    } else if (text == "") {
        warn("请填写加班成果");
    } else if (checkTarget.length > 0 && checkTarget.attr("fruitId") != fruitId) {
        warn("此加班对象已存在");
    } else {
        //如果此记录已存在，则先删除
        if (checkTr.length > 0) {
            checkTr.parents("tr").remove();
        }
        //插入tr
        var dataTr = "<tr><td>" + button + "</td><td>" + target + "</td><td><div>" + targetName + "</div></td><td>" + hour + "</td><td><div>" + text + "</div></td></tr>";
        var tr = $("#workAddFruitTable tr").eq(0);
        tr.after(dataTr);
        //清理提示
        if (tr.text() == "一条记录都没有") {
            tr.remove();
        }
        //关闭弹出层
        $("#workAddFruit").hide();
    }
}

/*行政人事-提交加班成果报告-编辑加班成果*/
function workAddFruitEdit(obj) {
    var form = document.workAddFruitForm;
    var postData = {
        "target": $(obj).attr("target"),
        "targetId": $(obj).attr("targetId"),
        "targetName": $(obj).parents("tr").children().eq(2).text(),
        "hour": $(obj).attr("hour"),
        "text": $(obj).attr("text"),
        "fruitId": $(obj).attr("fruitId")
    };
    layer('workAdd', 'fruit', postData);
}

/*行政人事-提交加班成果报告-删除加班成果*/
function workAddFruitDel(obj) {
    $(obj).parents("tr").remove();
}

function workAddSub() {
    //加班成果列表
    var fruit = {};
    $("[fruitId]").each(function () {
        var id = $(this).attr("fruitId");
        fruit[id] = {
            "target": $(this).attr("target"),
            "targetId": $(this).attr("targetId"),
            "hour": $(this).attr("hour"),
            "text": $(this).attr("text")
        }
    });
    //整理json数组
    var form = document.workAddTimeForm;
    var postData = {
        "fruit": fruit, "timeStart": form.timeStart.value, "timeEnd": form.timeEnd.value, "id": form.id.value
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=workAdd&fun=resultEdit", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

/*行政人事-提交外出成果报告-根据关键词获取外出对象*/
function workOutFruitShow(obj) {
    $(obj).siblings(".asynchronousMenu").show();
    workOutFruitKey(obj);
}

function workOutFruitKey(obj) {
    var target = document.workOutFruitForm.target.value; //外出对象
    var key = document.workOutFruitForm.targetId.value; //关键词
    $.post(root + "control/adIndex.html?cla=workOut&fun=fruitKey", {
        target: target, key: key
    }, function (data) {
        $(obj).siblings(".asynchronousMenu").children("ul").html(data.html);
    }, "json");
}

function workOutFruitName(obj) {
    var name = $(obj).html();
    var targetId = $(obj).attr("fruitTargetId");
    var input = $(obj).parents(".asynchronousMenu").siblings("[name=targetId]");
    input.val(name);
    input.attr("targetId", targetId);
}

function workOutFruitHide(obj) {
    $(obj).siblings(".asynchronousMenu").hide();
}

/*行政人事-提交外出成果报告-添加外出成果*/
function workOutFruitSub() {
    //组合tr
    var form = document.workOutFruitForm;
    var target = form.target.value;
    var targetId = form.targetId.getAttribute("targetId");
    var targetName = $("[fruitTargetId='" + targetId + "']").text();
    var hour = form.hour.value;
    var text = form.text.value;
    var fruitId = form.fruitId.value;
    var button = "<span fruitId='" + fruitId + "' target='" + target + "' targetId='" + targetId + "' hour='" + hour + "' text='" + text + "' onclick=\"workOutFruitEdit(this)\" class='spanButton'>编辑</span>" + "\n<span onclick=\"workOutFruitDel(this)\" class='spanButton'>删除</span>";
    var checkTarget = $("#workOutFruitTable").find("[targetId='" + targetId + "']");
    var checkTr = $("#workOutFruitTable").find("[fruitId='" + fruitId + "']");
    var checkPrice = /^[0-9]+(.[0-9]{1,2})?$/;
    if (target == "") {
        warn("请选择外出对象");
    } else if (form.targetId.value == "") {
        warn("请选择对象名称");
    } else if (targetName == "") {
        warn("未找到此对象名称");
    } else if (hour == "") {
        warn("请输入外出小时数");
    } else if (!checkPrice.test(hour)) {
        warn("外出小时数格式有误");
    } else if (text == "") {
        warn("请填写外出成果");
    } else if (checkTarget.length > 0 && checkTarget.attr("fruitId") != fruitId) {
        warn("此外出对象已存在");
    } else {
        //如果此记录已存在，则先删除
        if (checkTr.length > 0) {
            checkTr.parents("tr").remove();
        }
        //插入tr
        var dataTr = "<tr><td>" + button + "</td><td>" + target + "</td><td><div>" + targetName + "</div></td><td>" + hour + "</td><td><div>" + text + "</div></td></tr>";
        var tr = $("#workOutFruitTable tr").eq(0);
        tr.after(dataTr);
        //清理提示
        if (tr.text() == "一条记录都没有") {
            tr.remove();
        }
        //关闭弹出层
        $("#workOutFruit").hide();
    }
}

/*行政人事-提交外出成果报告-编辑外出成果*/
function workOutFruitEdit(obj) {
    var form = document.workOutFruitForm;
    var postData = {
        "target": $(obj).attr("target"),
        "targetId": $(obj).attr("targetId"),
        "targetName": $(obj).parents("tr").children().eq(2).text(),
        "hour": $(obj).attr("hour"),
        "text": $(obj).attr("text"),
        "fruitId": $(obj).attr("fruitId")
    };
    layer('workOut', 'fruit', postData);
}

/*行政人事-提交外出成果报告-删除外出成果*/
function workOutFruitDel(obj) {
    $(obj).parents("tr").remove();
}

/***行政人事-外出申请-提交现场照片***/
function workOutIco() {
    document.workOutIcoForm.file.click();
}

function workOutChange() {
    $("#workOutImg").attr("src", getFileUrl("workOutIcoFile"));
}

function workOutSub() {
    //外出成果列表
    var fruit = {};
    $("[fruitId]").each(function () {
        var id = $(this).attr("fruitId");
        fruit[id] = {
            "target": $(this).attr("target"),
            "targetId": $(this).attr("targetId"),
            "hour": $(this).attr("hour"),
            "text": $(this).attr("text")
        }
    });
    //整理json数组
    var form = document.workOutTimeForm;
    var postData = {
        "fruit": fruit, "timeStart": form.timeStart.value, "timeEnd": form.timeEnd.value, "id": form.id.value
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=workOut&fun=resultEdit", postData, function (data) {
        if (data.warn == 2) {
            var ico = document.workOutIcoForm.file.value;
            if (!!ico) {
                document.workOutIcoForm.submit();
            } else {
                window.location.reload();
            }
        } else {
            warn(data.warn);
        }
    }, "json");
}

/***财务会计-收支平衡-根据方向选择类型***/
function profitDirectionToType(obj) {
    $.post(root + "control/adIndex.html?cla=profit&fun=profitGetType", {
        direction: $(obj).val()
    }, function (data) {
        $(obj).siblings("[name=type]").html(data.type);
    }, "json");
}

/***代理日志-查询二级菜单***/
function getAgMenuTwo(obj) {
    $.post(root + "control/adIndex.html?cla=agLog&fun=getAgMenuTwo", {
        menuOne: $(obj).val()
    }, function (data) {
        $(obj).siblings("[name=menuTwo]").html(data.menuTwo);
    }, "json");
}

/***客户管理-客户列表-公私客转换***/
function publicClient(obj, khid) {
    $.post(root + "control/adIndex.html?cla=client&fun=publicClient", {
        khid: khid
    }, function (data) {
        if (data.warn == "更新成功") {
            $(obj).html(data.text);
            $("#nowAdName").html(data.name);
        }
        warn(data.warn);
    }, "json");
}


//展示输入框
function showInput(e) {
    $.post(root + 'control/adIndex.html?cla=component&fun=showInput', {}, function (res) {
        $(e).parent().before(res.html);
        $(e).css('display', 'none');
    }, 'json')
}

//展示添加按钮
function showAddButton(e) {
    let val = e.value;
    $.post(root + 'control/adIndex.html?cla=component&fun=showAddButton', {val: val}, function (res) {
        $(e).parent().after(res.html);
        $(e).parent().remove();
        $(".add-attr-button").css('display', 'inline-flex');
    }, 'json')
}

/***客户管理-客户列表-开票记录-更新发票扫描件***/
function clientInvoiceIcoFun(id) {
    var form = document.clientInvoiceIcoForm;
    form.clientInvoiceId.value = id;
    form.file.click();
}


/***标签删除**/
function del_this(e) {
    $(e).parent().remove();
}

/*附件-切换保密状态*/
function fileSecret(obj) {
    $.post(root + "control/adIndex.html?cla=file&fun=fileSecret", {
        id: $(obj).attr("id")
    }, function (data) {
        if (data.warn) {
            warn(data.warn);
        } else {
            $(obj).html(data.secret);
            $(obj).attr("title", data.title);
        }
    }, "json");
}

/***下载量***/
function downloadNum(name, id) {
    $.post(root + "control/data?type=" + name, {
        id: id
    });
}

/***系统设置-文章管理-根据一级分类返回二级分类***/
function getContentClassify(obj) {
    var type = obj.value;
    $.post(root + "control/adIndex.html?cla=content&fun=getContentClassify", {
        type: type
    }, function (data) {
        $(obj).siblings("[name=classify]").html(data.classify);
    }, "json");
}

/***系统设置-文章管理-将一级分类赋予输入框，返回二级分类，清理二级分类输入框***/
function giveContentType(obj) {
    var form = document.detailForm;
    form.type.value = obj.value;
    form.classify.value = "";
    $.post(root + "control/adIndex.html?cla=content&fun=getContentClassify", {
        type: obj.value
    }, function (data) {
        form.classifySelect.innerHTML = data.classify;
    }, "json");
}

/***系统设置-文章管理-将二级分类录入输入框***/
function giveContentClassify(obj) {
    document.detailForm.classify.value = obj.value;
}

// ul 缩放
function ulScal(obj, id) {
    let has = $(obj).nextAll('[pid="' + id + '"]')
    if (has.length > 0) {
        if (has.is(":hidden")) {
            $(obj).find('.arrow').css({
                'transform': 'rotate(180deg)',
            })
            has.show()
        } else {
            $(obj).find('.arrow').css({
                'transform': 'rotate(90deg)',
            })
            has.hide()
        }
    }

}

// 部门详情
function departmentDetail(obj, cla = 'department') {
    let id = $(obj).attr('data-id')
    if (id !== undefined && id.length > 0) {
        ulScal(obj, id)
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=detail", {
            id: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}

// 文档中心自动加载选中
function documentCenterChoice(id) {
    let obj = $("[data-id='" + id + "']")
    if (obj.length > 0) {
        ulScal(obj, id)
        $(obj).addClass('active')
        $.post(root + "control/adIndex.html?cla=documentCenter&fun=detail", {
            id: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}


function replaceDetail(obj, cla) {
    return departmentDetail(obj, cla)
}

// 职位
function replaceRight(obj, cla = 'job') {
    let api, id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
        $(obj).addClass('active')
        api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson'
        $.post(api, {
            objId: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}

/**
 * 树形缩放
 * @param obj
 */
function liZoom(obj) {
    let id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
    }
    window.event.stopPropagation();//阻止事件冒泡
}

/**
 * 获取右边内容
 * @param obj
 * @param cla
 */
function replaceContent(obj, cla) {
    let id = $(obj).attr('data-id');
    let api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson';
    if (id.length > 0) {
        id = id === 'all' ? '' : id
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $.post(api, {
            objId: id
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}


function containerLeftSearch(obj, type = 'department') {
    // 业务函数
    let keyword = obj.value.trim()
    let box = $('#container-left').find('ul[pid="0"]')
    $.post(root + 'control/adIndex.html?cla=' + type + '&fun=getContainerLeftJson', {
        type: type
    }, function (data) {
        if (keyword.length > 0) {
            //过滤掉data-id 是汉字的情况
            let hightlightText = (data.html).replace(new RegExp(`(?<!id=')(${keyword})`, 'g'), `<em class="keyword-match">$1</em>`);
            box.html(hightlightText)
        } else {
            box.html(data.html)
        }
    }, "json");
}

/**
 * 分类树形导航搜索
 */
function search_left(event) {
    let keyCode = event.keyCode
    let keyword = $('#container-left-search').val()
    //回车查询，关键词一样，则一直往下定位
    /*if (arg[1] !== undefined && arg[1].keyCode === 13) {
        findNextMatch();
    } else {
        findMatches(keyword, '.container-left li > .textcontent')
    }*/
    if(keyCode === undefined || keyCode === 13){
        let nowKeywordMatch = $('.classify-area').find('.now-keyword-match').first().text()
        if (nowKeywordMatch.length > 0 && nowKeywordMatch === keyword) {
            findNextMatch();
        } else {
            findMatches(keyword, '.container-left li > .textcontent')
        }
    }
}

/**
 * 已匹配关键字，回车查找下一个
 */
function findNextMatch() {
    let allMatch = document.querySelectorAll('.keyword-match')
    if (allMatch.length > 0) {
        console.log(allMatch.length)
        // 获取所有的keyword-match节点
        const keywordMatches = Array.from(allMatch);
        // 查找now-keyword-match在数组中的位置
        const nowKeywordMatchIndex = Number(keywordMatches.indexOf(document.querySelector('.now-keyword-match')));
        allMatch[nowKeywordMatchIndex].classList.remove('now-keyword-match');
        // 查找下一个匹配项
        let nextMatch = nowKeywordMatchIndex + 1;  // 下一个匹配项
        console.log(nextMatch)
        if (allMatch[nextMatch] === undefined) {
            nextMatch = 0
        }
        allMatch[nextMatch].scrollIntoView({behavior: "smooth", block: "nearest", inline: "center"});
        allMatch[nextMatch].classList.add('now-keyword-match');
        $(".search-count").html((nextMatch + 1) + '/' + allMatch.length);
    }
}

/**
 * 分类树形导航搜索，匹配所有关键字
 * @param keyword 关键字
 * @param querySelectorAll 搜索节点，例如：.container-left li > .textcontent
 * @returns {[]}
 */
function findMatches(keyword, querySelectorAll, scrollingArea = '.classify-area') {

    let matches = [];
    let $elements = $(querySelectorAll);
    let $scrollingArea = $(scrollingArea);
    let ico = `<span class='textcontent_ico'></span>`
    // 默认展开还是收起通过css控制

    // 清空搜索关键字
    if($elements.find('.keyword-match').length > 0) {
        //默认展示第一级
        $scrollingArea.find('li').show()
        // 先隐藏所有内容，默认收起
        $scrollingArea.find('.child-node').hide();
        $scrollingArea.find('.arrow').css({
            'transform': 'rotate(90deg)',
        })
        // 清空所有搜索
        $elements.each(function () {
            let $element = $(this);
            let htmlContent = $element.html();
            let plainText = htmlContent.replace(/<em class="keyword-match( now-keyword-match)?">|<\/em>/g, '');
            $element.html(plainText);
        });
    }
    // 重新匹配搜索
    if (keyword) {
        keyword = keyword.trim();
        $scrollingArea.find('.child-node').hide();
        $scrollingArea.find('.arrow-li').hide();
        $scrollingArea.find('.arrow-no-li').hide();
        $elements.each(function () {
            let $element = $(this);
            let prevli = $element.parents('.child-node').prev()

            let textContent = $element.text();
            let regex = new RegExp(keyword, 'gi');

            if (textContent.includes(keyword)) {
                let highlightedText = textContent.replace(regex, `<em class="keyword-match">$&</em>`);
                $element.html(ico + highlightedText);
                matches.push(this);
                //展开匹配项
                $element.parents('.arrow-no-li').show()
                $element.parents('.arrow-li').show()
                prevli.show()
                $element.parents('.child-node').css('display', 'block')
                prevli.find('.arrow').css({
                    'transform': 'rotate(180deg)',
                })
            }
        });

        if (matches.length > 0) {
            let text = '1' + '/'+ matches.length
            $(".search-count").html(text);
            matches[0].scrollIntoView({behavior: "smooth", block: "nearest", inline: "center"});
            $(matches[0]).find('.keyword-match').addClass('now-keyword-match');
        }else{
            let text = '0' + '/'+ matches.length
            $(".search-count").html(text);
        }
    }else{
        $(".search-count").html('0/0');
    }

    return matches;
}

/**
 * 保存分类搜索session
 * @param obj
 * @param cla
 * @param page
 */
function typeSession(obj, cla, page) {
    // 业务函数
    let keyword = obj.value
    $.post(root + 'control/adIndex.html?cla=' + cla + '&fun=typeSession', {
        page: page, keyword: keyword
    }, function (data) {
    }, "json");
}

// ul选择后赋值到指定ele函数
function selection(obj, ele) {
    let id = $(obj).attr('data-id')
    if (id.length > 0) {
        ulScal(obj, id)
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $('#' + ele).val(id)
    }
}

// 单个文本框更新
function textUpdate(obj, cla, fun) {
    let field = $(obj).attr('name'), val = $(obj).val()
    if (field.length > 0 && val.length > 0) {
        const url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun
        let params = {}
        // 判断是否有data-* 参数
        if ($(obj).data()) {
            Object.assign(params, $(obj).data())
            params[field] = val
        }
        $.post(url, params, function (resp) {
            if (resp.warn == 2) {
                if (resp.href) {
                    window.location.href = resp.href;
                } else {
                    window.location.reload();
                }
            } else {
                warn(resp.warn)
            }
        }, "json");
    }
}

/**
 * 删除行
 * @param e
 */
function decline(e) {
    $(e).parent().parent().remove();
}

function decRow(e) {
    $(e).parent().remove();
}

/**随机字符串**/
function randomString(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    let i = 0;
    for (i; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function button_method(e, power = '') {
    let type = $(e).data('type');
    if (type === 'add') {
        $('#uploadFile').click();
    } else if (type === 'delete') {
        let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
        let id = $("[name='fileId']").val();
        $.post(url, {
            id: id, power: power
        }, function (res) {
            if (res.warn === 2) {
                $("#singFileName").html('');
                $("#upload-ico").attr('src', root + "img/control/upload.svg");
                $("[name='fileId']").val('');
                $("#upload-ico").data('type', 'add');
            } else {
                warn(res.warn);
            }
        }, 'json')
    }
}

/**
 * 单文件上传
 */
function uploadSingleFile(formName, url) {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", window.top.document).show();
    let form = $("form[name='" + formName + "']")[0];
    let formData = new FormData(form);
    $.ajax({
        type: "POST",
        contentType: false,
        processData: false,
        url: url,
        data: formData,
        cache: false,
        success: function (res) {
            let result = JSON.parse(res);
            if (result.warn === 2) {
                $("[name='fileId']").val(result.data.id);
                $("#upload-ico").attr('src', root + "img/control/delete.svg");
                $("#singFileName").html(result.data.name);
                $("#upload-ico").data('type', 'delete');
            } else {
                warn(result.warn)
            }
        },
        error: function (e) {
            console.log(e)
            warn("上传失败");
        },
        complete: function () {
            $("[name='uploadFile']").val('');
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }
    });
}

//上传附件
function uploadAttachFile(formName, url, htmlId) {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", window.top.document).show();
    let form = $("form[name='" + formName + "']")[0];
    let formData = new FormData(form);
    $.ajax({
        type: "POST",
        contentType: false,
        processData: false,
        url: url,
        data: formData,
        cache: false,
        success: function (res) {
            let result = JSON.parse(res);
            if (result.warn === 2) {
                $("[name='" + formName + "'] #" + htmlId + "").before(result.data.html);
            } else {
                warn(result.warn)
            }
        },
        error: function (e) {
            console.log(e)
            warn("上传失败");
        },
        complete: function () {
            $("[name='" + formName + "'] [name='uploadFile']").val('');
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }
    });
}

//上传附件
function uploadAttachFileChunk(e, power, type, url, htmlId, blockId) {
    var fileList = $(e).prop('files'); //获取文件对象
    var arr = [];
    const chunkSize = 5 * 1024 * 1024;
    $.each(fileList, function (n, file) {
        var error = ''
        if ($('#' + blockId).find("[title='" + file.name + "']").length > 0) {
            error = '上传失败，已存在此附件'
        }
        var value = {
            'code': CryptoJS.MD5(file.name + file.size + file.lastModified).toString(),
            'target': type,
            'name': file.name,
            'size': file.size,
            'target_id': '',
            'chunks': Math.ceil(file.size / chunkSize),
            'power': power,
            'error': error,
        }
        arr.push(value)
    });
    $.post(root + 'control/adIndex.html?cla=share&fun=checkUpload', {fileInfo: JSON.stringify(arr)}, function (res) {
        if (res.warn === 2) {
            layer('share', 'uploadList', {'fileInfo': res.data, 'notClose': 1})
            //分片上传
            for (var i = 0; i < res.data.length; i++) {
                uploadChunks(fileList[i], res.data[i], url, htmlId)
            }
            $(e).val('')
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function allowDrop(ev) {
    ev.preventDefault();
}

function pasteFile(event, formName, url, htmlId, type = 'paste') {
    //等待动画
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, js_configurg.loading_time_out)
    $("#loading", window.top.document).show();
    var e = event || window.event;
    e.preventDefault()
    e.stopPropagation()
    if (type === 'drop') {
        var files = e.dataTransfer.files;//获取拖拽的文件

    } else {
        var files = e.clipboardData.files;//获取剪贴徳的图片信息
    }
    $.each(files, function (n, file) {
        let form = $("form[name='" + formName + "']")[0];
        let formData = new FormData(form);
        formData.append("uploadFile", file);
        $.ajax({
            type: "POST",
            contentType: false,
            processData: false,
            url: url,
            data: formData,
            cache: false,
            success: function (res) {
                let result = JSON.parse(res);
                if (result.warn === 2) {
                    $("[name='" + formName + "'] #" + htmlId + "").before(result.data.html);
                } else {
                    warn(result.warn)
                }
            },
            error: function (e) {
                console.log(e)
                warn("上传失败");
            },
            complete: function () {
                $("[name='" + formName + "'] [name='uploadFile']").val('');
                $("#loading", window.top.document).hide();
                clearTimeout(con);
            }
        });
    });


}

//删除附件
function delFile(id, cla, e) {
    let url = root + "control/adIndex.html?cla=fileUpload&fun=delFile";
    $.post(url, {
        id: id, power: cla
    }, function (res) {
        if (res.warn === 2) {
            $(e).parent().parent().remove();
        } else {
            warn(res.warn);
        }
    }, 'json')
}


function showState(event) {
    let state = $(".stateBlock").css('display');
    if (state == 'block') {
        $(".stateBlock").hide();
    } else {
        $(".stateBlock").show();
    }
}

/**
 * 仅周一
 */
function onlyMonday() {
    $(".layui-laydate-content table tr td:nth-child(1)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(3)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(4)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(5)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(6)").addClass('laydate-disabled')
    $(".layui-laydate-content table tr td:nth-child(7)").addClass('laydate-disabled')
}

/** 页面打印 */
function printPage(cla, fun = 'printPage', formName = 'listForm') {
    let body = '', data = $('[name="' + formName + '"]').serializeArray()
    data.forEach(ele => {
        body += ele.value + ';'
    });
    if (body.length > 0) {
        let url = root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun + '&body=' + body
        window.open(url)
    } else {
        warn('请选择你要打印的条目')
        return false
    }
}

/******获取表中选中的数据*******/
function get_checked_box(cla, fun, formName) {
    let arr = [];
    $("[name='" + formName + "'] input:checkbox[name='listId[]']:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
        layer(cla, fun, {listId: vals});
    } else {
        msg('请选择需要数据');
    }
}

// 复制
function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name=" + name + "]").val(val);
}

/**
 * 员工选择器-删除
 */
function del_staff(e) {
    let id = $(e).data('stid')
    let boxid = $(e).data('boxid'), hidden = $("#" + boxid + " #" + boxid + "layer")
    //$("#staff-box [name='staff[]']")
    id += ';';
    let stid = hidden.val();
    stid = stid.replace(id, '');
    hidden.val(stid);
    $(e).prev().remove();
    $(e).remove();
}

/**操作url参数****/
var urlHelper = {
    /****获取参数***/
    getUrlParam: function (url, ref) {
        let str = "";
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return "";
        }
        str = url.substr(url.indexOf('?') + 1);
        let arr = str.split('&');
        let i = '';
        for (i in arr) {
            let paired = arr[i].split('=');
            if (paired[0] == ref) {
                return paired[1];
            }
        }
        return "";
    }, /****增加参数***/
    addUrlParam: function (url, ref, value) {
        // 如果没有参数
        if (url.indexOf('?') == -1) {
            return url + "?" + ref + "=" + value;
        }
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return url + "&" + ref + "=" + value;
        }
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        let i = 0;
        for (i; i < arr_param.length; i++) {
            let paired = arr_param[i].split('=');
            if (paired[0] == ref) {
                paired[1] = value;
                arr_param[i] = paired.join('=');
                break;
            }
        }

        return base + "?" + arr_param.join('&');
    }, /****删除参数***/
    delUrlParam: function (url, ref) {
        // 如果不包括此参数
        if (url.indexOf(ref) == -1) {
            return url;
        }
        var arr_url = url.split('?');
        var base = arr_url[0];
        var arr_param = arr_url[1].split('&');
        var index = -1;
        let i = 0;
        for (i; i < arr_param.length; i++) {
            var paired = arr_param[i].split('=');
            if (paired[0] == ref) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            return url;
        } else {
            arr_param.splice(index, 1);
            return base + "?" + arr_param.join('&');
        }
    }
};

/***详情页选项卡切换***/
function liTab(cla, fun, id) {
    //切换导航
    $("#liMenu > ul > li").removeClass("pageMenuHover");
    $("[liMenu=" + fun + "]").addClass("pageMenuHover");
    //切换内容页
    $("[page_content]").hide();
    if ($("[page_content=" + fun + "]").length >= 1) {
        $("[page_content=" + fun + "]").show();
    } else {
        $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun + "&id=" + id, function (data) {
            if (data.warn) {
                warn(data.warn);
            } else if ($("[page_content=" + fun + "]").length >= 1) { //防止后台推送多次数据
                $("[page_content=" + fun + "]").html(data.html);
            } else {
                $("#liMenu").after("<div class='pageDiv' page_content='" + fun + "'>" + data.html + "</div>");
            }
        }, "json");
    }
}

$("#record").mouseover(function () {
    showState();
});
$("#record").mouseout(function () {
    showState();
});
//点击非下拉区域隐藏
$(document, window.parent.document).bind('click', function (e) {
    let target = $("#searchMenu", window.parent.document);
    if (!target.is(e.target) && target.has(e.target).length === 0) {
        $("#searchMenuText", window.parent.document).hide();
        $("#bigAutocompleteContent", window.parent.document).hide();
    }
    target = $("#user", window.parent.document);
    if (!target.is(e.target) && target.has(e.target).length === 0) {
        $(".userList", window.parent.document).hide();
    }
});

//默认结算周期
function settlementDayDefault(e) {
    let type = e.value;
    let days = $(e).parents('li').find("[name='settlementDay']").val()
    if (type === '月结' && days === '') {
        $("[name='settlementDay']").val('30')
    }
}

//对输入金额进行校验
function digitalFiltering(obj, num) {
    // 过滤输入内容
    var inputValue = obj.value;
    var filteredValue = inputValue.replace(/[^\d.]/g, ""); // 清除非数字和非小数点的字符
    filteredValue = filteredValue.replace(/^\./g, ""); // 验证第一个字符是数字而不是小数点
    filteredValue = filteredValue.replace(/\.{2,}/g, "."); // 只保留第一个.清除多余的
    filteredValue = filteredValue.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); // 清除多余的小数点，保留最后一个
    filteredValue = filteredValue.replace(new RegExp(`^(\\-)*(\\d+)\\.(\\d{${num}}).*$`), '$1$2.$3'); // 只能输入指定小数位

    // 限制整数部分的最大长度为12位
    var integerPart = filteredValue.split(".")[0];
    if (integerPart.length > 12) {
        integerPart = integerPart.slice(0, 12);
        var decimalPart = filteredValue.split(".")[1] || "";
        filteredValue = integerPart + "." + decimalPart;
    }
    // 更新输入框的值
    obj.value = filteredValue;
}

function fluctuateKeyDown(inputField, num) {
    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
        var currentValue = parseFloat(inputField.value) || 0;
        var decimalPlaces = 0;
        var decimalIndex = inputField.value.indexOf('.');
        if (decimalIndex !== -1) {
            decimalPlaces = inputField.value.length - decimalIndex - 1;
        }
        var step = 1 / Math.pow(10, decimalPlaces);
        // 检查是否按下了上下键
        if (event.key === 'ArrowUp') {
            currentValue = (currentValue + step).toFixed(num) * 1;
            event.preventDefault();
        } else if (event.key === 'ArrowDown') {
            currentValue = (currentValue - step).toFixed(num) * 1;
            event.preventDefault();
        }
        currentValue = currentValue.toString()
        currentValue = currentValue.replace(/[^\d.]/g, ""); // 清除非数字和非小数点的字符
        currentValue = currentValue.replace(/^\./g, ""); // 验证第一个字符是数字而不是小数点
        currentValue = currentValue.replace(/\.{2,}/g, "."); // 只保留第一个.清除多余的
        currentValue = currentValue.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); // 清除多余的小数点，保留最后一个
        currentValue = currentValue.replace(new RegExp(`^(\\-)*(\\d+)\\.(\\d{${num}}).*$`), '$1$2.$3'); // 只能输入两个小数
        // 更新输入框的值
        inputField.value = currentValue;
    }
}


/**
 * 科目选择器--弹窗
 * @param e
 * @param name
 * @param isShow
 */
function chooseSubject(e, name, isShow) {
    let rowId = $("[name='" + name + "']").attr('id');
    layer('component', 'subject', {isShow: isShow, rowId: rowId})
}

/**
 *科目选择器--弹窗点击科目事件
 * @param e
 */
function chooseSubjectId(e) {
    let id = $(e).data('id');
    let name = $(e).data('name');
    $(e).parent().find("li").css('background-color', 'white');
    $(e).css('background-color', "rgb(242, 242, 242)");
    $("[name='chooseId']").val(id);
    $("[name='chooseName']").val(name);
}

/**
 * 科目选择器--弹窗确认按钮事件
 * @param selectorId
 * @returns {boolean}
 */
function confirmBtn(selectorId) {
    let id = $("[name='chooseId']").val();
    let name = $("[name='chooseName']").val();
    if (!id) {
        msg('请选择科目', 'error')
        return false;
    }
    let hiddenName = $("#" + selectorId).data('name');
    $("#" + selectorId).siblings("input[name='" + hiddenName + "']").val(id);
    $("#" + selectorId).val(name);
    $('#componentSubject').hide()
}

/**
 * 筛选区域 收起，展开
 */
function cutOut(e) {
    let form = $(e).parents("form")
    if (form.find(".more-container").is(":hidden")) {
        form.find(".more-container").show(); //如果元素为隐藏,则将它显现
        $(e).html('收起')
    } else {
        form.find(".more-container").hide(); //如果元素为显现,则将其隐藏
        $(e).html('展开')
    }
}

/**
 * 批量打印
 * @param cla 菜单
 * @param options 可选参数
 * @returns {*|jQuery|HTMLElement}
 */
function batchPrint(cla, options = {}) {
    let formName = options.formName || 'listForm';
    let fun = options.fun || 'batchPrint';
    let targetId = options.targetId || '';
    let lists = $("input:checkbox[name='listId[]']:checked").map(function () {
        return $(this).val();
    }).get().join(',');
    return layer('printTemplate', 'selectTemplate', {lists: lists, cla: cla, fun: fun, targetId: targetId});
}


function printJump() {
    let formObject = {};
    $.each($("form[name='printTemplateSelectTemplateForm']").serializeArray(), function (i, field) {
        formObject[field.name] = field.value;
    })
    formObject['lists'] = window.btoa(formObject['lists'])
    let params = new URLSearchParams(formObject)
    return window.open(root + 'control/adIndex.html?' + params)
}

/**
 * 保存临时内容
 * @param verifyUrl
 * @param form
 * @param url
 * @param verifyUrl
 */
// function saveTemp(cla, fun = 'edit', formName = 'EditForm') {
//     const formData = $('[name="' + formName + '"]').serialize()
//     const data = {
//         'cla': cla,
//         'fun': fun,
//         'body': formData,
//     }
//     $.post(root + 'control/adIndex.html?cla=homepage&fun=saveTemp', data, function (res) {
//         if (res.warn === 2) {
//             window.location.reload()
//         } else {
//             msg(res.warn, 'error')
//         }
//     }, 'json')
// }
//
// function getTemp(cla, fun = 'edit', formName = 'EditForm') {
//     $.post(root + 'control/adIndex.html?cla=homepage&fun=getTemp', {'cla': cla, 'fun': fun}, function (res) {
//         console.log()
//         if (res.warn === 2) {
//             if (Object.keys(res.data).length > 0) {
//                 cxDialog('当前记录存在草稿信息，是否加载?', function () {
//                     delTemp(root + 'control/adIndex.html?cla='+cla+'&fun='+fun+'Edit');
//                     const formData = res.data
//                     $.each(formData, function (key, val) {
//                         $("[name=" + formName + "]").find('[name="' + key + '"]').val(val)
//                     })
//                 }, function () {
//                     delTemp(root + 'control/adIndex.html?cla='+cla+'&fun='+fun+'Edit');
//                 })
//             }
//         } else {
//             msg(res.warn, 'error')
//         }
//     }, 'json')
// }
// function delTemp(url){
//     // 保存后删除草稿
//     $.post(root + 'control/adIndex.html?cla=homepage&fun=delTemp', {str: url}, function () {
//     })
//
// }

//form支持多表单提交，中间用,隔开，url为提交地址
function subFormVerify(form, url, verifyUrl) {
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, lib_configurg.loading_time_out);
    $("#loading", window.top.document).show();
    //串联表单
    var formName = form.split(",");
    var forms = [];
    for (var i = 0; i < formName.length; i++) {
        if (formName[i] !== "") {
            forms = forms.concat($("[name=" + formName[i] + "]"));
        }
    }
    var jsonData = getFormJson(forms);
    var obj = event.target;//发生点击事件的当前html节点
    //异步提交数据
    $.post(verifyUrl, {serialize_json: JSON.stringify(jsonData)}, function (data) {
        if (data.warn === 2 || data.warn === '2') {
            subForm(form, url)
        } else {
            if (data.allow === 1 || data.allow === '1') {
                cxDialog(data.warn, () => {
                    subForm(form, url)
                }, () => {
                    // click no callback
                });
            } else {
                cxDialog(data.warn, false, () => {
                    // click no callback
                });
            }
        }
        $("#loading", window.top.document).hide();
        clearTimeout(con);
    }, "json");
}

/**
 * 删除上传进度
 * @param e
 * @param id
 */
function uploadAborted(e, id) {
    $.post(root + 'control/adIndex.html?cla=share&fun=uploadAborted', {id}, function (res) {
        if (res.warn === 2) {
            $(e).closest('ul').remove()
            $("[progress-id='" + id + "']").find('.del-row-button').click()
            uploadProgressCheck()
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function uploadProgressCheck() {
    let finish = 1;
    $('#shareUploadList [class*="-scale"]').each(function () {
        // 检查当前元素的文本内容是否等于 "100%"
        if ($(this).text().trim() !== '100%') {
            finish = 0
        }
    });
    if (finish) {
        let suc = $('#shareUploadList [class*="-scale"]').length
        let fail = $('#shareUploadList [class*="upload-error"]').length
        setTimeout(function () {
            $('#shareUploadList').find('.progress-incomplete').html('上传已完成，成功'+suc+'个，失败'+fail+'个。')
            $('#shareUploadList').find('.progress-completed').show()
        }, 500);
    }
    if ($('.upload-aborted-text').length === 0) {
        $('.no-data-div').show()
    }
}

/**
 * 上传分片
 * @param file
 * @param info
 * @param url
 * @param htmlId
 */
function uploadChunks(file, info, url, htmlId = '') {
    if (!info.error) {
        const chunkSize = 5 * 1024 * 1024;
        const name = file.name;
        const size = file.size;
        const chunks = Math.ceil(size / chunkSize);
        let chunk = info.chunk * 1;

        const start = chunk * chunkSize;
        const end = Math.min(start + chunkSize, size);
        const chunkData = file.slice(start, end);
        const formData = new FormData();
        formData.append('file', chunkData);
        formData.append('name', name);
        formData.append('size', size);
        formData.append('chunks', chunks);
        chunk += 1;
        formData.append('chunk', chunk);
        formData.append('info', JSON.stringify(info));
        info.chunk = chunk
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function (data) {
                if (data.warn == 1) {
                    return false
                } else if (data.warn == 2) {
                    $('#' + info.id).css('width', data.progress + '%')
                    $('.' + info.id + '-scale').text(data.progress + '%')
                    if (data.progress === 100) {
                        //$('.' + info.id + '-close').hide()
                        uploadProgressCheck()
                    }
                    if (data.state === 1) {
                        if (htmlId) {
                            $("#" + htmlId + "").before(data.html);
                        } else {
                            // 如果是详情页附件页卡
                            var pagediv = $('#windowMaskView').closest('[pagediv]').attr('pagediv')
                            //获取查询结果区域的ID号
                            var searchFormId = (pagediv ? pagediv : 'home')+'SearchHtml';
                            //更新查询结果
                            var pageNow = $('[searchformhtml=' + searchFormId + '] .pageButton .pageNow');//当前页
                            if (pageNow.length === 1) {//如果存在分页
                                pageNow.click();
                            } else {
                                $('[searchformhtml=' + searchFormId + ']').find('input[type=submit]').click();
                            }
                            //关闭当前编辑弹窗
                            //$(obj).parents('.win').find('.winClose').click();
                            if (data.msg) {
                                msg(data.msg, 'info')
                            }
                        }
                        if ($.cookie('warn')) {
                            warn($.cookie('warn'));
                            $.cookie('warn', '');
                        }
                    } else if (chunk < chunks) {
                        uploadChunks(file, info, url, htmlId);
                    }
                } else {
                    msg(data.warn, 'error')
                }
            },
            error: function () {
                msg('上传失败', 'error')
            }
        });
    }
}

// 判断空
function isEmpty(value) {
    if (value === undefined || value === null) {
        return true;
    } else if (typeof value === 'string' && value.trim() === '') {
        return true;
    } else if (Array.isArray(value) && value.length === 0) {
        return true;
    } else if (typeof value === 'object' && Object.keys(value).length === 0) {
        return true;
    }
    return false;
}

// 删除表单已选择的内容
function removeSelectedContent(formName) {
    $("form[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        $(this).parents("tr").remove()
    });
}

/**********************************列表页***************************************************************************/
function liClick(obj) {
    //obj=this，即从函数调用处传this，传的函数调用处的对象。如果用event.target，则是事件发生处的对象，两个对象不一定相同
    $(obj).siblings().removeClass("choose");
    $(obj).addClass("choose");
    //更新表控件区高亮样式
    var index = $(obj).index();//当前控件索引
    var buttonUl = $(obj).parent(".body").parent(".right").siblings(".left").children(".buttonBody").children("ul");
    buttonUl.children().removeClass("choose");
    buttonUl.children("li:nth-of-type(" + (index + 1) + ")").addClass("choose");
}

function liButtonClick(obj) {
    //更新表控件区高亮样式
    $(obj).siblings().removeClass("choose");
    $(obj).addClass("choose");
    //更新表体高亮样式
    var index = $(obj).index();//当前控件索引
    var body = $(obj).parent("ul").parent(".buttonBody").parent(".left").siblings(".right").children(".body");
    body.children().removeClass("choose");
    body.children("ul:nth-of-type(" + (index + 1) + ")").addClass("choose");

    var buttonUl = $(obj).parent("ul").parent(".buttonBody").parent(".left").siblings(".left").children(".buttonBody").children("ul");
    buttonUl.children().removeClass("choose");
    buttonUl.children("li:nth-of-type(" + (index + 1) + ")").addClass("choose");
}

//调整列宽
function liWidth(obj) {
    if (event.button === 0) {//只有按住鼠标左键才触发事件
        //参数准备
        var clientX = event.clientX;//鼠标x坐标
        var th = $(obj).parent("li");//当前表头单元格
        var index = th.index();//当前表头单元格的索引
        var thWidth = th.innerWidth();//当前表头单元格宽度
        var headWidth = th.parent("ul").width();//表头总长
        var bodyUl = th.parent("ul").parent(".head").next(".body").children("ul");//表体所有的行
        var bodyWidth = bodyUl.width();//表体总长
        var totalUl = th.parent("ul").parent(".head").siblings(".head").children("ul"); //合计宽度调整
        var width = thWidth;//单元格列宽，需保存到数据库
        var minWidth = 36;//单元格最低不能低于50px
        var x = 0;//鼠标横向移动距离
        //生成基线和移动线
        var right = th.parent("ul").parent(".head").parent(".right");
        var baseLineLeft = th.offset().left - th.parent("ul").parent(".head").scrollLeft() - th.parent("ul").offset().left + thWidth - 2;
        right.append("\
     	<div class='baseLine' style='left:" + baseLineLeft + "px'></div>\
     	<div class='blueLine' style='left:" + baseLineLeft + "px'></div>\
     	");
        //鼠标移动
        document.onmousemove = function (event) {
            x = event.clientX - clientX;
            right.children(".blueLine").css({"left": baseLineLeft + x});
        }
        //鼠标松开
        document.onmouseup = function (event) {
            //释放移动事件
            this.onmousemove = null;
            this.onmouseup = null;
            //清理标识线
            right.children(".baseLine").remove();
            right.children(".blueLine").remove();
            //保存列宽到数据库
            width = thWidth + x;
            if (width <= minWidth) {
                width = minWidth;
                x = width - thWidth;
                warn("已到最小宽度" + minWidth + "px");
            }
            if (width == thWidth) {
                //宽度未改变，不做任何处理
            } else {
                //console.log(headWidth,bodyWidth)
                //为表头单元格设定列宽
                th.innerWidth(width);
                //为表体单元格设定列宽
                bodyUl.children("li:nth-of-type(" + (index + 1) + ")").innerWidth(width);
                totalUl.children("li:nth-of-type(" + (index + 1) + ")").innerWidth(width);
                //设定表头ul总长
                th.parent("ul").width(headWidth + x);
                //设定表体ul总长
                bodyUl.width(bodyWidth + x);
                totalUl.width(bodyWidth + x);
                //调整窗口
                liWinFun(right.parent(".li"));
                var fieldData = $(obj).parent().data();//列字段名称
                //保存列宽到服务器
                var postData = {
                    page: th.parent("ul").parent(".head").parent(".right").parent(".li").attr("page"),
                    name: fieldData.key,
                    width: width
                };
                $.post(root + "control/adIndex.html?cla=installSearch&fun=width", postData, function (data) {
                    if (data.warn == 2) {
                        warn(data.tip);
                    } else {
                        warn(data.warn);
                    }
                }, "json");
            }
        }
    }
}

//调整固定列的宽
function fixLiWidth(obj) {
    if (event.button === 0) {//只有按住鼠标左键才触发事件
        //参数准备
        var clientX = event.clientX;//鼠标x坐标
        var th = $(obj).parent("li");//当前表头单元格
        var index = th.index();//当前表头单元格的索引
        var thWidth = th.innerWidth();//当前表头单元格宽度
        var headWidth = th.parent("ul").width();//表头总长
        var bodyUl = th.parent("ul").parent(".buttonHead").next(".fixBody").children("ul");//表体所有的行
        var bodyWidth = bodyUl.width();//表体总长
        var totalUl = th.parent("ul").parent(".buttonHead").siblings(".buttonHead").children("ul"); //合计宽度调整
        var width = thWidth;//单元格列宽，需保存到数据库
        var minWidth = 36;//单元格最低不能低于50px
        var x = 0;//鼠标横向移动距离
        //生成基线和移动线
        var fixDiv = th.parent("ul").parent(".buttonHead").parent(".left");
        var baseLineLeft = th.offset().left - th.parent("ul").parent(".buttonHead").scrollLeft() - th.parent("ul").offset().left + thWidth - 2;
        fixDiv.append("\
     	<div class='baseLine' style='left:" + baseLineLeft + "px'></div>\
     	<div class='blueLine' style='left:" + baseLineLeft + "px'></div>\
     	");
        //鼠标移动
        document.onmousemove = function (event) {
            x = event.clientX - clientX;
            fixDiv.children(".blueLine").css({"left": baseLineLeft + x});
            //在移动中直接改变盒子宽度，达到影响两边盒子的动态效果
            width = thWidth + x;
            if (width <= minWidth) {
                width = minWidth;
                x = width - thWidth;
                warn("已到最小宽度" + minWidth + "px");
            }
            //为表头单元格设定列宽
            th.innerWidth(width);
            //设定表头ul总长
            th.parent("ul").width(headWidth + x);
            th.parent("ul").parent(".buttonHead").parent(".left").width(headWidth + x);
            //设定表体ul总长
            bodyUl.width(bodyWidth + x);
            totalUl.width(bodyWidth + x);
        }
        //鼠标松开
        document.onmouseup = function (event) {
            //释放移动事件
            this.onmousemove = null;
            this.onmouseup = null;
            //清理标识线
            fixDiv.children(".baseLine").remove();
            fixDiv.children(".blueLine").remove();
            //保存列宽到数据库
            if (width == thWidth) {
                //宽度未改变，不做任何处理
            } else {
                //调整窗口
                liWinFun(fixDiv.parent(".li"));
                var fieldData = $(obj).parent().data();//列字段名称
                //保存列宽到服务器
                var postData = {
                    page: th.parent("ul").parent(".buttonHead").parent(".left").parent(".li").attr("page"),
                    name: fieldData.key,
                    width: width
                };
                $.post(root + "control/adIndex.html?cla=installSearch&fun=width", postData, function (data) {
                    if (data.warn == 2) {
                        warn(data.tip);
                    } else {
                        warn(data.warn);
                    }
                }, "json");
            }
        }
    }
}

//表格行双击事件
function lidbClick() {
    let obj = arguments[0]
    //处理固定列的情况，让lidb完全显示
    let sign = arguments[1]
    let lidbWidth = $(obj).width() - 24
    let lidbStyle = sign === 'fix' ? " style='width: " + lidbWidth + "px;' " : ''
    //关闭所有文字弹窗
    $(".lidb").parent("li").html($(".lidb").html()).css({"overflow": "hidden"});
    //切换到弹窗，展示完整内容
    $(obj).html("\
    <div title='已展示单元格完整内容' class='lidb' " + lidbStyle + ">" + $(obj).html() + "</div>\
    <div title='返回单元格' class='lidbClose' onclick='lidbClose(this)'>×</div>\
    ");
    $(obj).css({"overflow": "visible"});
    //取消当前页面上的文本选中
    window.getSelection().removeAllRanges();
}

//关闭文字弹窗
function lidbClose(obj) {
    //获取文字
    var word = $(obj).siblings(".lidb").html();
    //恢复li标签的文字和css
    $(obj).parent("li").html(word).css({"overflow": "hidden"});
}

//表格滚动条
function liScroll(obj) {
    //获取表体的滚动条顶部位置
    var top = $(obj).scrollTop();
    //获取表体的滚动条左侧位置
    var left = $(obj).scrollLeft();
    //表体纵向滚动时同步左侧控件区
    $(obj).parent().siblings('div').children(".buttonBody").scrollTop(top);
    //表体横向滚动时同步表头
    $(obj).prev().scrollLeft(left);
    $(obj).next().scrollLeft(left);
    //如果宽度发生变化，则同步表头，因为scrollWidth不包含margin，所以两者相减一直会有差额
    var head = obj.previousElementSibling.children[0];
    head.style.marginRight = (obj.scrollWidth - head.scrollWidth) + "px";
    //如果高度变化，则同步左侧控件区
    var buttonBody = obj.parentNode.previousElementSibling.children[1].children[0];
    buttonBody.style.marginBottom = (obj.scrollHeight - buttonBody.scrollHeight) + "px";
}

//窗口尺寸变化时调整表格尺寸
function liWin(id) {
    //修正表高度
    var li = $("#" + id);
    liWinFun(li);
    //窗口缩放时修正表高度
    $(window).resize(function () {
        liWinFun(li);//窗口缩放时必须传入对象li，而不能只传一个ID号，否则检索不到该对象
    });
    //列表悬停
    li.find('.buttonBody li').hover(function () {
        let index = $(this).index();
        listHover(li, index, true)
    }, function () {
        let index = $(this).index();
        listHover(li, index, false)
    });
    li.find('.body ul').hover(function () {
        let index = $(this).index()
        listHover(li, index, true)
    }, function () {
        let index = $(this).index()
        listHover(li, index, false)
    });
    //固定窗格增加阴影
    let leftLen = $('#' + id + ' > .left').length
    $('#' + id + ' > .left:nth-child(' + leftLen + ')').css('box-shadow', '6px 0px 10px -10px #aaa');
}

function listHover(li, index, show) {
    if (show) {
        li.find('.left > .buttonBody > ul > li:nth-of-type(' + (index + 1) + ')').addClass('list-hover')
        li.find('.right > .body > ul:nth-of-type(' + (index + 1) + ')').addClass('list-hover')
    } else {
        li.find('.left > .buttonBody > ul > li:nth-of-type(' + (index + 1) + ')').removeClass('list-hover')
        li.find('.right > .body > ul:nth-of-type(' + (index + 1) + ')').removeClass('list-hover')
    }
}

//表格尺寸调整函数
function liWinFun(li) {
    //获取当前浏览器滚动条宽度
    var scrollWidth = scrollWidthFun();
    //获取左侧控件区
    var liButton = li.children(".left");
    //获取表头
    var liHead = li.children(".right").children(".head");
    //获取表体
    var liBody = li.children(".right").children(".body");
    //先放大表体高度，因为winBody.scrollHeight无法计算所有子元素高度
    liBody.height(10000);
    //获取窗口body
    var winBody = $("#body");
    //表体高度=表体原有高度-窗口隐藏高度(窗口内容高度-窗口可视高度)
    var height = liBody.height() - (winBody.get(0).scrollHeight - winBody.height());
    //更改表体的可视高度
    if (height <= 0) {
        height = 0;
    }
    liBody.height(height);
    if (liBody.get(0).scrollWidth > liBody.innerWidth()) {
        liButton.children(".buttonBody").height(height - scrollWidth);
        liButton.children(".scrollLeft").height(scrollWidth);
    } else {
        liButton.children(".buttonBody").height(height);
        liButton.children(".scrollLeft").height(0);
    }
    //如果表体出现纵向滚动条，则定义表头尾部滚动条替代区宽度
    if (liBody.get(0).scrollHeight > liBody.height()) {
        liHead.children(".scrollHead").width(scrollWidth);
    } else {
        liHead.children(".scrollHead").width(0);
    }
}

//获取当前浏览器滚动条宽度
function scrollWidthFun() {
    //创建一个容器
    var scrollDiv = $('<div>').css({
        'width': '100px', 'height': '100px', 'overflow': 'scroll', 'position': 'absolute', 'top': '-9999px'
    }).appendTo('body');
    //计算滚动条宽度
    var width = scrollDiv[0].offsetWidth - scrollDiv[0].clientWidth;
    //删除容器
    scrollDiv.remove();
    //返回
    return width;
}

/**********************************列名称设置****************************************************************************/
//单选
function installBox() {
    //参数准备
    var form = $(event.target).parents("form");
    //全选框状态设定
    if (form.find("[name='name\[\]']").length == form.find("[name='name\[\]']:checked").length) {
        form.find("[name=installAll]").prop('checked', true);
    } else {
        form.find("[name=installAll]").prop('checked', false);
    }
}

//切换类型
function installType() {
    //参数准备
    var obj = event.target;
    var type = obj.value;
    var form = $(obj).parents("form");
    var page = form.attr("page");

    //请求服务器
    $.post(root + "control/adIndex.html?cla=installSearch&fun=installType", {page: page, type: type}, function (data) {
        if (data.warn == 2) {
            //刷新列字段列表
            form.find(".body").html(data.body);
            //判定全选按钮
            if (data.checkAll == "checked") {
                $bool = true;
            } else {
                $bool = false;
            }
            form.find("[name=installAll]").prop('checked', $bool);
            //关键词查询初始化
            installSearchKey = "";
            $("#installSearchSpan").html(0 + "/" + 0);
        } else {
            warn(data.warn);
        }
    }, "json");
}

//切换位置
function installList() {
    //参数准备
    var obj = event.target;
    var form = $(obj).parents("form");
    var ulNow = $(obj).parents("ul");
    var ulNowIndex = $(ulNow).index();
    var index = $(obj).val() - 1;
    var length = form.find(".body>ul").length;
    //移动到目标位置
    if (!Number.isInteger(index) || index < 0) {
        warn("序号必须为正整数且大于零");
    } else {
        if (index >= ulNowIndex) {
            index++;//如果目标位置比当前位置大，因当前位置目前是占位的，所以要加1
        }
        if (index < length) {
            $(ulNow).insertBefore(form.find(".body>ul:eq(" + index + ")"));
        } else {//如果是最后一个，则使用appendChild
            form.children(".body").append(ulNow);
        }
    }
    //修正序号
    form.find("[name='list']").each(function (index) {
        var list = index + 1;
        $(this).val(list);
    });
}

//查询
function installSearchEnter() {
    if (event.keyCode === 13) {
        installSearch();
    }
}

function installSearch() {
    //参数准备
    var form = $(event.target).parents("form");
    //取value值，并消除字符串左右空格
    var search = form.find("[name=search]").val().trim();
    if (search == "") {
        warn("请填写列名称关键词");
    } else {
        if (typeof installSearchKey === 'undefined' || installSearchKey != search) {
            installSearchKey = search;//全局变量，查询关键词
            installSearchAll = 0;//全局变量，查询总数
            installSearchNow = 0;//全局变量，当前位置
            //查询
            form.find("[name='name\[\]']").each(function () {
                var name = $(this).data('name');
                var ul = $(this).parent("label").parent("li").parent("ul");
                if (name.includes(installSearchKey)) {
                    installSearchAll++;
                    if (installSearchAll == 1) {
                        var c = "highlightNow";
                        installSearchNow = 1;
                        //滚动到选中位置
                        form.children(".body").scrollTop(ul.offset().top - form.children(".body").children("ul:eq(0)").offset().top);
                    } else {
                        var c = "highlight";
                    }
                    var regexp = new RegExp(installSearchKey, "gi");
                    //$&在replace()方法中被约定为正则表达式所匹配的文本
                    var html = name.replace(regexp, "<span class='" + c + "'>$&</span>");
                    $(this).parents("ul").children(":eq(1)").html(html);
                } else {
                    //如果本字段没有查询的关键词，则消除可能存在的之前查询的关键词的高亮效果
                    $(this).parents("ul").children(":eq(1)").html(name);
                }
            });
        } else if (installSearchAll > 0) {
            if (installSearchNow < installSearchAll) {
                installSearchNow++;
            } else {
                installSearchNow = 1;
            }
            //将之前选中的高亮效果设为普通高亮效果
            form.find(".highlightNow").removeClass("highlightNow").addClass("highlight");
            //设置下一个选中的高亮效果
            var now = form.find(".highlight:eq(" + (installSearchNow - 1) + ")");
            now.removeClass("highlight").addClass("highlightNow");
            //滚动到该位置
            form.children(".body").scrollTop(now.parent("li").parent("ul").offset().top - form.children(".body").children("ul:eq(0)").offset().top);
        }
        //计数
        $("#installSearchSpan").html(installSearchNow + "/" + installSearchAll);
    }
}

//列名称设置-提交
function installConfirm() {
    //参数准备
    var form = $(event.target).parents("form");
    var page = form.attr("page");
    var type = form.find("[name=type]:checked").val();
    var left_columns = form.find("[name=left_columns]").val();
    //列名称
    var install = {};
    form.find("[name='name\[\]']").each(function () {
        var name = $(this).val();
        if ($(this).prop("checked")) {
            var display = 1;
        } else {
            var display = 0;
        }
        install[name] = {
            "display": display,
            "alias": $(this).parents("ul").children(":eq(2)").children("input[type='text']").val(),
            "list": $(this).parents("ul").children(":eq(3)").children("input[type='number']").val(),
            "width": $(this).parents("ul").children(":eq(4)").children("input[type='number']").val()
        }
    });
    //整理json数组
    var postData = {
        "page": page, "type": type, "left_columns": left_columns, "install": install
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=installSearch&fun=installConfirm", postData, function (data) {
        if (data.warn == 2) {
            window.location.reload();
        } else {
            warn(data.warn);
        }
    }, "json");
}

//列名称设置-恢复默认设置
function restoreDefault() {
    //参数准备
    var form = $(event.target).parents("form");
    var page = form.attr("page");
    //整理json数组
    var postData = {
        "page": page
    };
    //请求服务器
    $.post(root + "control/adIndex.html?cla=installSearch&fun=restoreDefault", postData, function (data) {
        if (data.warn == 2) {
            form.find('.body').html(data.data.body)
            form.find("[form='install']").attr(data.data.checkAll)
            form.find("[name='left_columns']").val(data.data.left_columns)
        } else {
            warn(data.warn);
        }
    }, "json");
}

/**********************************列点击排序****************************************************************************/
// 界面排序
$(document).on('click', '[li-sort-key] > .cursor', function () {
    var li = $(this).parent()
    var nowSort = li.find('.table-sort').attr('sort')
    var asc = nowSort === 'desc' || nowSort === undefined ? 1 : 0
    switchSorting(li, asc)
})
$(document).on('click', '[li-sort-key] > .table-sort > i', function () {
    var li = $(this).parent().parent()
    var className = $(this).attr('class');
    let nowSort = li.find('.table-sort').attr('sort')
    if (className.includes('asc')) {
        if (nowSort !== 'asc') {
            switchSorting(li, 1)
        }
    } else if (className.includes('desc')) {
        if (nowSort !== 'desc') {
            switchSorting(li, 0)
        }
    }
})

function switchSorting(li, asc) {
    //获取表体的滚动条左侧位置
    var left = li.closest(".li").find(".right").find(".body").scrollLeft();

    let sortSpan = li.find('.table-sort'), ascObj = li.find('.table-sort-asc'), descObj = li.find('.table-sort-desc')
    if (!asc) {
        ascObj.removeClass('table-sort-asced')
        descObj.addClass('table-sort-desced')
        sortSpan.attr('sort', 'desc')
    } else {
        ascObj.addClass('table-sort-asced')
        descObj.removeClass('table-sort-desced')
        sortSpan.attr('sort', 'asc')
    }
    li.siblings().find('i').removeClass('table-sort-asced table-sort-desced')
    // 开始排序
    var pageStr = li.parents("ul").parents(".li").attr("page")
    var pageArr = pageStr.split("-")
    var page = pageArr[0];
    var searchForm = pageArr[1] + 'Form';
    var key = li.data('key')
    var sort = asc ? 'asc' : 'desc';
    var form = li.parents("#body").find("[name='" + searchForm + "']")
    form.find("input[name='list_sort_key']").val(key)
    form.find("input[name='list_sort']").val(sort)
    form.find("input[type=submit]").click();

    //保持列表滚动的位置
    // 在这里执行需要等待异步请求结束后的代码，函数将会被执行一次，之后就会被销毁
    $(document).one('ajaxStop', function () {
        //保存排序
        $.post(root + 'control/adIndex.html?cla=installSearch&fun=saveSort', {pageStr: pageStr, list_sort_key: key, list_sort: sort}, function (res) {}, 'json')

        var right = $("[page='" + pageStr + "']").find(".right")
        //表体横向滚动时同步表头
        right.children('div').scrollLeft(left);
    });
}

/** home 查询条件重置 */
function searchResetting(obj, cla, fun, json) {
    $.post(root + 'control/adIndex.html?cla=' + cla + '&fun=' + fun, json, function (res) {
        $(obj).parents('.search-container').find('.search-input-list').html(res.html)
    }, 'json')
}

/**********************列表每页行数设置**********************/
// 同步数据
function pageSetInput(element) {
    var num = $(element).val()
    var pageStr = $(element).data("page")
    var pageArr = pageStr.split("-")

    var searchForm = pageArr[1] + 'Form';
    var form = $(element).parents("#body").find("[name='" + searchForm + "']")

    $.post(root + 'control/adIndex.html?cla=homepage&fun=setPageNum', {num, pageStr}, function (res) {
        if (res.code === 0) {
            $(element).siblings('.page-num-tip').html(res.warn)
            $(element).siblings('.page-num-tip').show()
        } else {
            form.find("input[type=submit]").click();
            msg(res.warn)
        }
    }, 'json')
}

/***********************编辑页列表操作*****************************/
/**
 * 复制行
 * @param element
 * @param data
 */
function cloneRows(element, data = {}) {
    var row = $(element).closest('tr')
    var par = {}
    if (data.hasOwnProperty('para')) {
        par = data.para
    }
    if (data.hasOwnProperty('copy')) {
        for (const item of data.copy) {
            par[item] = row.find("[name='" + item + "[]']").val()
        }
    }
    if (data.hasOwnProperty('nodeTextByClass')) {
        for (const item of data.nodeTextByClass) {
            par[item] = row.find("." + item).text()
        }
    }
    $.post(root + 'control/adIndex.html?cla=' + data.cla + '&fun=' + data.fun, par, function (res) {
        $(element).closest('tr').after(res.html);
        resetNumber($(element).closest('tbody'))
        if(data.callback){
            eval(data.callback);
        }
    }, 'json');
}

function resetNumber(element, listClass = 'list-number') {
    element.find('.'+listClass).each(function (index) {
        $(this).text(index + 1);
    });
}

/**
 * 删除编辑表格行
 * @param e
 */
function delTableRow(e) {
    let table = $(e).closest('table')
    $(e).closest('tr').remove();
    resetNumber(table)
}

/**
 * 删除行
 * @param element
 * @param data
 */
function delRows(element, data = {}) {
    var siblingLen = $(element).closest('tr').siblings('tr').length
    var row = $(element).closest('tr')
    var tbody = row.closest('tbody')
    if (siblingLen === 0) {
        if (data.hasOwnProperty('empty')) {
            for (const item of data.empty) {
                row.find("[name='" + item + "[]']").val('')
            }
        }
        if (data.hasOwnProperty('emptyByClass')) {
            for (const item of data.emptyByClass) {
                row.find("." + item).text('')
            }
        }
    } else {
        row.remove();
        resetNumber(tbody)
    }
}

/**
 * 删除父级元素
 * @param e
 */
function del_li(e) {
    $(e).parent().remove();
}

/**
 * 编辑页面数据合计
 * @param parentSelector
 * @param currentSelector
 * @param type
 * @returns {number}
 */
function pageEditTotal(parentSelector, currentSelector, type = 'val') {
    var total = 0;
    $(parentSelector).find(currentSelector).each(function () {
        if(type === 'val'){
            total += parseFloat($(this).val());
        }else{
            total += parseFloat($(this).text());
        }
    });
    return total
}

function reloadTemplateOption(menuFour, targetId){
    let obj = $(document).find('#template-option'),
        edit = $(document).find('#printTemplateEdit'),
        operate = $(document).find('#printTemplateOperate')
    if (obj.length > 0) {
        fetchData(root+'control/adIndex.html?cla=printTemplate&fun=getOption', {menuFour: menuFour, targetId: targetId}, function (response) {
            edit.remove()
            operate.remove()
            obj.html(response.html)
        })
    }
}
/*************************************/
function changeCoid(coid){
    if (!coid){
        msg('this account is not found','error');
    }else{
        $.post(root + "control/adIndex.html?cla=homepage&fun=updateCoid", {
            'coid': coid
        }, function (data) {
            if (data.warn === 2) {
                window.parent.location.href = root + 'control/adIndex.html';
            } else {
                msg(data.warn,'error');
            }
        }, "json")
    }
}

/**
 * 账套切换前置操作
 * @param obj
 * @param coid
 */
function preValidationCoid(obj,coid) {
    var callback = $(obj).data('fun')
    $.post(root + "control/adIndex.html?cla=homepage&fun=preValidationCoid", {
        'coid': coid
    }, function (data) {
        if (data.warn === 2) {
            // 执行回调函数
            if(callback){
                eval(callback);
            }
        } else {
            cxDialog(data.warn, () => {
                $.post(root + "control/adIndex.html?cla=homepage&fun=updateCoid", {
                    'coid': coid
                }, function (data) {
                    if (data.warn === 2) {
                        var titleLi = $(window.top.document).find('#iframeTitle').find('li').not(".iframeTitleNow");
                        // 遍历每个元素并检查其显示状态
                        titleLi.each(function () {
                            var $liDiv = $(this).find('div');
                            var name = $liDiv.attr('title');
                            // 缩短ul
                            $("#iframeTitle > ul").css({
                                width: "-=137px"
                            });
                            // 多个iframe删除
                            $("[goback='" + name + "']").remove();
                            $("[iframeName='" + name + "']").remove();
                            $(this).remove(); //删除顶部页卡
                            // 判断上级是否存在
                            if($('#iframeTitle').find('.iframeTitleNow').length === 0) {
                                $("[iframeName=主页]").css("display", "block"); //显示我的桌面iframe
                                $("#homepage").addClass("iframeTitleNow"); //高亮我的桌面顶部页卡
                                $("[iframeHref]").removeClass("frameLeftHover"); //清理左侧导航高亮选择效果
                            }
                        });
                        //修正右侧翻页箭头
                        fixRightArrow()
                        $(window.frameElement).attr("src", $("#renovate").attr("url"));
                        // 执行回调函数
                        if(callback){
                            eval(callback);
                        }
                    } else {
                        msg(data.warn,'error');
                    }
                }, "json")
            }, () => {
                // click no callback
            });
        }
    }, "json")
}
// 经纬度地区获取
function convertRegion(latlng) {
    var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
    var input = latlng.split(',');
    var location = new TMap.LatLng(Number(input[0]), Number(input[1]));
    geocoder.getAddress({ location: location }) // 将给定的坐标位置转换为地址
        .then((result) => {
            //console.log(result)
            $("[name='region']").val(result.result.address_component.province+'-'+result.result.address_component.city+'-'+result.result.address_component.district);
        });
}
function togglePassword(obj) {
    let toggleIcon = $(obj);
    let passwordInput = toggleIcon.siblings('input');
    if (passwordInput.attr('type') === 'password') {
        passwordInput.attr('type','text')
        // 更改图标为显示图标
        toggleIcon.attr('src', root+'img/svg/pass_show.svg')
    } else {
        passwordInput.attr('type','password')
        // 更改图标为隐藏图标
        toggleIcon.attr('src', root+'img/svg/pass_hide.svg')
    }
}

